Borislav Hadzhiev
Thu Jun 16 2022·2 min read
Photo by Sandra Seitamaa
Use a list comprehension to convert a list of strings to a list of integers,
e.g. new_list = [int(item) for item in my_list]
. In the list comprehension, we
iterate over each item in the original list and pass it to the int()
class to
convert it to an integer.
my_list = ['10', '20', '30', '40'] new_list = [int(item) for item in my_list] print(new_list) # 👉️ [10, 20, 30, 40]
In the example, we call the int()
class with each item in the list and return
the result.
The int class returns an integer object constructed from the provided number or string argument.
Alternatively, you can use the map()
function.
To convert a list of strings to a list of integers:
int()
class and the list to the map()
function.map()
function will pass each item of the list to the int()
class.my_list = ['10', '20', '30', '40'] new_list = list(map(int, my_list)) print(new_list) # 👉️ [10, 20, 30, 40]
The map() function takes a function and an iterable as arguments and calls the function on each item of the iterable.
This approach is a bit more implicit than using a list comprehension.
Notice that we passed the map
object to the list()
class to convert it to a
list.
for
loop.my_list = ['10', '20', '30', '40'] for index, item in enumerate(my_list): my_list[index] = int(item) print(my_list) # 👉️ [10, 20, 30, 40]
The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index, and the second - the item.
On each iteration, we use the index to update the value of the list item to an integer.