String list to int list Python | Example code

Use the map function to convert String list to int list in Python. To get a list of int you need to convert the result from a map to a list. This is the most elegant, pythonic, and recommended method to do this conversion.

Example string list to int list Python

Simple example code.

Using map()

test_list = ['1', '2', '3', '4', '5']

res = list(map(int, test_list))

print(res)
print(type(res))

Output:

String list to int list Python

Using list comprehension

str_list = ['1', '4', '3', '6', '7'] 

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

print(int_list)

Output: [1, 4, 3, 6, 7]

Using for loop

Using a naive method to perform the conversion.

str_list = ['1', '4', '3', '6', '7']


for i in range(0, len(str_list)):
    str_list[i] = int(str_list[i])

print(str_list)

Output: [1, 4, 3, 6, 7]

Do comment if you have any doubts and suggestions on this Python string list topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.