1

I want to take an input say 7 8 9 5 12 17 as separate integers in an array ar[]. I have tried a=input() ar.append(a.split(" ")) but it just stores the numbers as strings. And I can't find a way to convert these integers directly while appending. Please help thanks in advance.

4 Answers4

0

This should do it:

a=input()
ar = map(int, a.split(" "))

See Python: How do I convert an array of strings to an array of numbers?

eskatos
  • 4,174
  • 2
  • 40
  • 42
0

To create a proper python list object, you can do

ar = [int(i) for i in input().split()]

Otherwise, Do it this way

ar = map(int, input().split())

You can also strip extra whitespace if needed. Do

ar = map(int, input().strip().split())
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
0

You can do it by list comprehension.

ar = [int(x) for x in a.strip().split()]

Here, we first strip the whitespace from the end and the beginning of the input a and then perform split(). It will return list of all the numbers in a as strings. Then using list comprehension, we convert all the numbers obtained as string to integers.

Example:

For a as ' 12 34 45 12 56 ',

>>> ar = [int(x) for x in a.strip().split()]
>>> ar
[12, 34, 45, 12, 56]

Note: split() operation returns a list of strings. We ourselves will have to perform the conversion of those strings to integers.

Rahul Gupta
  • 46,769
  • 10
  • 112
  • 126
0

The built-in function map(function, iterable, ..) can be used here to apply the int() function all over.

ar = map(int, a.split(" "))
Himanshu Mishra
  • 8,510
  • 12
  • 37
  • 74