python

Convert a List of Strings to List of Integers in Python

Converting a list of strings to a list of integers in Python can be a useful technique for data manipulation and processing. In this post, we will explore different methods to convert a list of strings to a list of integers in Python, including using list comprehension and the map() function.

Convert a List of Strings to List of Integers in Python

To convert a List of Strings to a List of Integers in Python:

  1. Create a List of String values. eg: str_list = ["1", "2", "3", "4", "5"].
  2. Use a List comprehension to convert it to Integers List. [int(x) for x in str_list].

Convert Using List comprehension

List comprehension is a concise way to create a new list in Python by iterating over an existing list and applying a specific operation to each element. To convert a list of strings to a list of integers using list comprehension, you can use the int() function to convert each string to an integer, and then create a new list containing the integers. Here is an example:

str_list = ["1", "2", "3", "4", "5"]

int_list = [int(x) for x in str_list]

print(int_list)

Output

[1, 2, 3, 4, 5]

In this example, the str_list variable contains a list of strings, and the int_list variable is created using a list comprehension. The int() function is applied to each element x of the str_list using int(x). The final result is a new list containing the integers.

List comprehension is a powerful feature of Python, it is easy to read and understand. However, If the list is large it could be a performance issue, as it will iterate over the whole list and convert each element one by one.


Convert using map() function

Alternatively, you can use the map() function:

str_list = ["1", "2", "3", "4", "5"]

int_list = list( map(int, str_list) )

print(int_list)

Output

[1, 2, 3, 4, 5]

This code will take a list of strings, convert each element to an integer, and produce a new list of integers. The list 'str_list' contains five strings, each being a number from 1 to 5. The 'map' function takes two arguments, the first being a function to apply and the second being iterable.

In this case, the function 'int' is being applied to each string in the list 'str_list.' The result of the 'map' function is a map object, which is then converted to a list by the 'list' function. The result of this is a list of integers, where each element is the integer representation of the original element in 'str_list.' The final line prints this list of integers, which will be [1, 2, 3, 4, 5].


Both of these methods use a list comprehension (or map()) to iterate through the original list of strings, convert each string to an integer using the int() function, and return a new list containing the integers.

Was this helpful?