How to convert a list to int in Python

In this tutorial we’ll show you to convert a list of string values to an integer type

Updated March 29, 2023

Hello and welcome to this beginner’s tutorial on how to convert a list to an integer in Python. Sometimes, you may have a list of string values that you want to convert to an integer type. In this tutorial, we will show you how to do that using Python programming language.

Method 1: Using a For Loop

The simplest way to convert a list of strings to integers in Python is to use a for loop. Here’s an example:

# Using a for loop
string_list = ['1', '2', '3', '4', '5']

int_list = []
for string in string_list:
    int_list.append(int(string))

print(int_list)

In this code, we define a list of string values called string_list. We create an empty list called int_list, then use a for loop to iterate over each string in string_list. We append each string converted to an integer using the int() function to int_list. Finally, we print int_list, which contains the converted integer values.

Method 2: Using the map() Function

The map() function in Python applies a function to each element in a list and returns a new list with the results. We can use this function to convert a list of strings to integers. Here’s an example:

# Using the map() function
string_list = ['1', '2', '3', '4', '5']

int_list = list(map(int, string_list))

print(int_list)

In this code, we define a list of string values called string_list. We use the map() function to apply the int() function to each element in string_list. We convert the resulting map object to a list using the list() function and store it in int_list. Finally, we print int_list, which contains the converted integer values.

Method 3: Using List Comprehension

List comprehension is a concise way to create a list in Python. We can use list comprehension to convert a list of strings to integers. Here’s an example:

# Using list comprehension
string_list = ['1', '2', '3', '4', '5']

int_list = [int(string) for string in string_list]

print(int_list)

In this code, we define a list of string values called string_list. We use list comprehension to apply the int() function to each element in string_list. We store the resulting list in int_list. Finally, we print int_list, which contains the converted integer values.

Conclusion

In this tutorial, we have shown you three different methods to convert a list of strings to integers in Python. We have covered using a for loop, the map() function, and list comprehension. It’s important to choose the right method that suits your needs and the context in which you’re working.

Keep practicing these methods and try to use them in your own projects. Remember that practice makes perfect, and the more you practice, the better you will get at Python programming. Thank you for reading, and happy coding!

Hey! Do you love Python? Want to learn more about it?
Let's connect on Twitter or LinkedIn. I talk about this stuff all the time!