Search code snippets, questions, articles...

Convert all string values in a list to integers using python

In this post, we will convert all the string values in a list to numbers using python. The fastest and pythonic way to do it is by using the map() function as below code snippet
my_list = ["20", "30", "50", "90"]

my_list = list(map(int, my_list))

# -> [20, 30, 50, 90]

We are using the map() function of python to convert all string type elements to integer type values. We are passing int keyword and the list to map() function for the conversion. This method is returning us the integer type values as a list. Remember that the map() function returns a map, we are converting it to a list using the list() function.

There are more ways to do the same. Some of them are described below.

str_list = ["10", "20", "30", "40"]

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

# -> [10, 20, 30, 40]
We can also use python for loop to convert all list elements to integer type values. In the above code, we have a list str_list that contains multiple list items in string format. After converting them to integer type we are getting them in results named variable.
Was this helpful?
Programming Feeds
Learn something new everyday on Devsheet