How to convert all strings in a list to ints in Python
In this tutorial, we are going to learn about how to convert all strings in a list to integers in Python.
Consider, we have a following prices list:
prices = ['2', '3', '4']
Now, we need to convert the above list of strings to a list of integers like this:
[2, 3, 4]
Converting list of strings to integers
To convert the list of strings to integers, we can use the built-in
map() function in Python.
Here is an example:
prices = ['2', '3', '4'] int_map = map(int, prices) int_list = list(int_map) print(int_list)
[2, 3, 4]
In the code above, the map() function applies the
int() to each iterable in the list and converts it to ints, then we have passed the
map() output to
list() function to convert it to a list.
Similarly, we can also do it by using a list comprehension syntax in Python.
prices = ['2', '3', '4'] int_list = [int(el) for el in prices] print(int_list)