converting list of string to list of integer
66,966
Solution 1
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
.
Solution 2
One way is to use list comprehensions:
intlist = [int(x) for x in stringlist]
Solution 3
this works:
nums = [int(x) for x in intstringlist]
Solution 4
You can try:
x = [int(n) for n in x]
Solution 5
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
Author by
Shriram
Updated on May 22, 2020Comments
-
Shriram almost 4 years
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]
-
Rob I about 12 years+1 but did you mean
map(int,yourlist)
? -
Matt Fenwick about 12 yearsThis doesn't work.
int
is not a method on strings. -
Silviu about 12 yearsSorry I edited it... This is actually what I meant :)
-
Matt Fenwick about 12 yearsIt's not wrong, but I generally wouldn't reuse
x
like that. -
Silviu about 12 yearsCan you give me an example why?
-
quodlibetor about 12 yearsdo you mean
map(int, input().split())
, or does py3k automatically convert space-separated input into a list? -
ch3ka about 12 yearsno, 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.
-
georg about 12 years+1,
[int(x) for x in input().split()]
to conform OP's specs.