Convert a list of strings to a list of integers in Python


Borislav Hadzhiev

Thu Jun 16 20222 min read

Convert a list of strings to a list of integers in Python #

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]
List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

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:

  1. Pass the int() class and the list to the map() function.
  2. The map() function will pass each item of the list to the int() class.
  3. The new list will only contain integer values.
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.

If you want to convert the items of the list in place instead of creating a new list with integers, use a 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.