Use map() to convert strings to integers in a Python list

avatar

Borislav Hadzhiev

Last updated: Jun 16, 2022

banner

Photo from Unsplash

Use map() to convert strings to integers in a Python list #

To 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 = ['1', '2', '3', '4'] new_list = list(map(int, my_list)) print(new_list) # 👉️ [1, 2, 3, 4]

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

We used the int class to convert the strings in the list to integers.

main.py
print(int('1')) # 👉️ 1 print(int('2')) # 👉️ 2

The int class returns an integer object constructed from the provided number or string argument.

The constructor returns 0 if no arguments are given.

Alternatively, you can use a list comprehension to convert a list of strings to a list of integers.

main.py
my_list = ['1', '2', '3', '4'] new_list = [int(item) for item in my_list] print(new_list) # 👉️ [1, 2, 3, 4]
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.

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 = ['1', '2', '3', '4'] for index, item in enumerate(my_list): my_list[index] = int(item) print(my_list) # 👉️ [1, 2, 3, 4]

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.