views:

102

answers:

3

Hello.

What is the easiest way to convert list with str into list with int in python? =) For example, we have to convert ['1','2','3'] to [1,2,3]. Of course, we can use "for:", but it's too easy =)

+8  A: 

Python 2.x:

map(int, ["1", "2", "3"])

Python 3.x (in 3.x, map returns an iterator, not a list as in 2.x):

list(map(int, ["1", "2", "3"]))

map documentation: 2.6, 3.1

codeape
I'm under the impression that `map` is generally disliked. It was even almost removed from Python 3.
pafcu
+8  A: 
[int(i) for i in str_list]
SilentGhost
The `)` at the end is wrong, but otherwise +1
Chris Lutz
+1 I really like `map`, but generators are way more readable.
Adam Matan
+4  A: 

You could also use list comprehensions:

new = [int(i) for i in old]

Or the map() builtin function:

new = map(int, old)

Or the itertools.imap() function, which will provide a speedup in some cases but in this case just spits out an iterator, which you will need to convert to a list (so it'll probably take the same amount of time):

import itertools as it
new = list(it.imap(int, old))
Chris Lutz