How to Convert a List of Strings to a List of Integers in Python

If you want to convert a list of strings to a list of integers, you can use different techniques:

  1. Use the map() function
  2. Use a list comprehension to create a new list from your initial list
  3. Use the enumerate() function

Use the map() function to convert a list of strings to a list of integers

The map built-in function returns an iterator that applies a function to every item of iterable. This approach

my_list = ['1','2','3','4','5'] new_list = list(map(int, my_list)) print(new_list) #[1,2,3,4,5]
Code language: Python (python)

Note that you must pass the map object into the list class to convert it to a list. While this approach is great, list comprehensions are a great alternative.

Use a list comprehension to convert a list of string to a list of ints

A list comprehension is a quick and efficient way to apply a modification to every element of a list. It’s often used to avoid using for loops over and over, which could impact the readability of our code.

In our case, we want to convert a list of strings to a list of integers using the int() operator, which allows us to get the number from a string representation of a number.

my_list = ['1','2','3','4','5'] new_list = [int(element) for element in my_list] print(new_list) #[1,2,3,4,5]
Code language: Python (python)

Use enumerate()

This last option is harder to grasp, but it does the job as well. By using the enumerate() function, you can get the same result. The enumerate function is defined as follows:

def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1
Code language: Python (python)

If we apply this function to our list, we get a list of tuples with the index (starting from 0 by default) and our values from our initial list.

my_list = ['1', '2', '3', '4'] list_enumerate = (list(enumerate(my_list))) #[(0, '1'), (1, '2'), (2, '3'), (3, '4')]
Code language: Python (python)

We can iterate over these results to get our final list

my_list = ['1', '2', '3', '4'] list_enumerate = list(enumerate(my_list)) new_list = [] for index, element in list_enumerate: new_list.append(int(element)) print(new_list) #[1,2,3,4]
Code language: Python (python)

It works, but it’s far from being the more straightforward solution, in my opinion.

Leave a Reply

Your email address will not be published. Required fields are marked *