16

How do I convert a space separated integer input into a list of integers?

Example input:

list1 = list(input("Enter the unfriendly numbers: "))

Example conversion:

['1', '2', '3', '4', '5']  to  [1, 2, 3, 4, 5]
okm
  • 23,575
  • 5
  • 83
  • 90
Shriram
  • 4,711
  • 6
  • 20
  • 22

7 Answers7

35

map() is your friend, it applies the function given as first argument to all items in the list.

map(int, yourlist) 

since it maps every iterable, you can even do:

map(int, input("Enter the unfriendly numbers: "))

which (in python3.x) returns a map object, which can be converted to a list. I assume you are on python3, since you used input, not raw_input.

ch3ka
  • 11,792
  • 4
  • 31
  • 28
  • 1
    +1 but did you mean `map(int,yourlist)` ? – Rob I Apr 27 '12 at 13:48
  • do you mean `map(int, input().split())`, or does py3k automatically convert space-separated input into a list? – quodlibetor Apr 27 '12 at 14:23
  • no, I assumed that the digits are entered without whitespace, as the provided example suggests. In fact, I did not post this as a solution, I just wanted to point out that the second argument to map() does not have to be a list, any iterable works. – ch3ka Apr 27 '12 at 14:26
15

One way is to use list comprehensions:

intlist = [int(x) for x in stringlist]
Maehler
  • 6,111
  • 1
  • 41
  • 46
3

this works:

nums = [int(x) for x in intstringlist]
cobie
  • 7,023
  • 11
  • 38
  • 60
1

You can try:

x = [int(n) for n in x]
Silviu
  • 835
  • 14
  • 22
1

Say there is a list of strings named list_of_strings and output is list of integers named list_of_int. map function is a builtin python function which can be used for this operation.

'''Python 2.7'''
list_of_strings = ['11','12','13']
list_of_int = map(int,list_of_strings)
print list_of_int 
Shashank Singh
  • 719
  • 6
  • 11
0
 l=['1','2','3','4','5']

for i in range(0,len(l)):
    l[i]=int(l[i])
Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81
-1

Just curious about the way you got '1', '2', '3', '4' instead of 1, 2, 3, 4. Anyway.

>>> list1 = list(input("Enter the unfriendly numbers: "))
Enter the unfriendly numbers: 1, 2, 3, 4
>>> list1 = list(input("Enter the unfriendly numbers: "))
Enter the unfriendly numbers: [1, 2, 3, 4]
>>> list1
[1, 2, 3, 4]
>>> list1 = list(input("Enter the unfriendly numbers: "))
Enter the unfriendly numbers: '1234'
>>> list1 = list(input("Enter the unfriendly numbers: ")) 
Enter the unfriendly numbers: '1', '2', '3', '4'
>>> list1
['1', '2', '3', '4']

Alright, some code

>>> list1 = input("Enter the unfriendly numbers: ")
Enter the unfriendly numbers: map(int, ['1', '2', '3', '4'])
>>> list1
[1, 2, 3, 4]
okm
  • 23,575
  • 5
  • 83
  • 90