Skip to content

Convert the list of strings to int Python | Example code

  • by

Use the map() function to convert the list of strings to int in Python. Maps each string to an int and Converts mapped output to a list of ints.

How to convert a list of strings to ints in Python

A simple example code converting a list of strings to ints converts each string in the list into an integer.

s_list = ["1", "2", "3"]

i_map = map(int, s_list)

res = list(i_map)

print(res)

Output:

Convert the list of strings to int Python

Or you can use a list comprehension and the int() function. Here’s an example:

str_list = ["1", "2", "3", "4", "5"]
int_list = [int(x) for x in str_list]
print(int_list)

If any of the strings in str_list are not valid integers, you will get a ValueError exception. To handle this case, you can use a try-except block to catch the exception and handle it appropriately. Here’s an example:

str_list = ["1", "2", "3", "four", "5"]
int_list = []

for x in str_list:
    try:
        int_list.append(int(x))
    except ValueError:
        print(f"{x} is not a valid integer")

print(int_list)

Do comment if you have any doubts or suggestions on this Python example code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading