Convert all strings in a list to int
In Python, I want to convert all strings in a list to integers.
So if I have:
results = ['1', '2', '3']
How do I make it:
results = [1, 2, 3]
Solution 1:
Use the map
function (in Python 2.x):
results = map(int, results)
In Python 3, you will need to convert the result from map
to a list:
results = list(map(int, results))
Solution 2:
Use a list comprehension:
results = [int(i) for i in results]
e.g.
>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]
Solution 3:
You can easily convert string list items into int items using loop shorthand in python
Say you have a string result = ['1','2','3']
Just do,
result = [int(item) for item in result]
print(result)
It'll give you output like
[1,2,3]