views:

210

answers:

5

How can I convert a list of strings (each of which represents a number, i.e. [‘1’, ‘2’, ‘3’]) into numeric values.

+15  A: 

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

Tadeusz A. Kadłubowski
It should pointed out that `map` is a built in function that applies the function `int` to every element of your list. Then returns a list of the results of that function.
Andrew Cox
I keep forgeting that functional programming stuff like map exists, Thanks for reminding me of another nice way to modify lists.
Dan Goldsmith
This is homework. Why provide a full answer? Why not provide hints, a direction and -- above all -- a reference to the int function?
S.Lott
@S.Lott: It's been a while since I've had any homework. Man, what kind of school is that where the task is to look up a library function and have problems with doing it? BTW: I'll edit references to official docs.
Tadeusz A. Kadłubowski
@Andrew: it returns list of results only in py2k, in py3k it returns a generator that needs to be converted into list explicitly.
SilentGhost
+3  A: 
>>> int('5')
5
Lennart Regebro
+2  A: 

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

alanlcode
+5  A: 

As Long as the strings are of the form '1' rather than 'one' then you can use the int() function.

Some sample code would be

strList = ['1','2','3']
numList = [int(x) for x in strList]

Or without the list comprehension

strList = ['1','2','3']
numList = []
for x in strList:
    numList.append(int(x))

Both examples iterate through the list on strings and apply the int() function to the value.

Dan Goldsmith
+8  A: 

Use int() and a list comprehensions:

>>> i = ['1', '2', '3']
>>> [int(k) for k in i]
[1, 2, 3]
Swingley