Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert all strings in a list to int

Tags:

python

list

int

In Python, I want to convert all strings in a list to integers.

So if I have:

results = ['1', '2', '3'] 

How do I make it:

results = [1, 2, 3] 
like image 861
Michael Avatar asked Sep 10 '11 00:09

Michael


People also ask

How do you convert a list to an int in Python?

Use int() function to Convert list to int in Python. This method with a list comprehension returns one integer value that combines all elements of the list.

How do I print a list in int?

If you want to print a list of integers, you can use a map() function to transform them into strings. Then you can use the join() method to merge them into one string and print them out.


1 Answers

Use the map function (in Python 2.x):

results = map(int, results) 

In Python 3, you will need to convert the result from map to a list:

results = list(map(int, results)) 
like image 72
cheeken Avatar answered Sep 23 '22 00:09

cheeken