The input
function in python
returns the entire line as a str
.
So, if you enter a space separated list of ints, the input
function will return the entire line as a string.
>>> a = input()
1 2 3 4 5
>>> type(a)
<class 'str'>
>>> a
'1 2 3 4 5'
If you want to save this as a list of integers, you have to follow the following procedure.
>>> a = input()
1 2 3 4 5
>>> a
'1 2 3 4 5'
Now, we need to separate the numbers in the string, i.e. split the string.
>>> a = a.strip().split() # .strip() will simply get rid of trailing whitespaces
>>> a
['1', '2', '3', '4', '5']
We now have a list
of strings
, we have to convert it to a list
of ints
. We have to call int()
for each element of the list
, and the best way to do this is using the map
function.
>>> a = map(int, a)
>>> a
<map object at 0x0081B510>
>>> a = list(a) # map() returns a map object which is a generator, it has to be converted to a list
>>> a
[1, 2, 3, 4, 5]
We finally have a list
of ints
This entire process is mostly done in one line of python
code:
>>> a = list(map(int, input().strip().split()))
1 2 3 4 5 6
>>> a
[1, 2, 3, 4, 5, 6]