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

avatar

Borislav Hadzhiev

Last updated: Jun 16, 2022

banner

Photo from Unsplash

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

To convert a list of strings to a list of integers:

  1. Use a list comprehension to iterate over the list.
  2. Convert each string to an integer by passing them to the int() class.
  3. The new list will only contain integer values.
main.py
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.
main.py
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 with 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.
main.py
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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.