tags:

views:

189

answers:

5

I have a list with numeric strings, like so:

numbers = ['1', '5', '10', '8'];

I would like to convert every list element to integer, so it would look like this:

numbers = [1, 5, 10, 8];

I could do it using a loop, like so:

new_numbers = [];
for n in numbers:
    new_numbers.append(int(n));
numbers = new_numbers;

Does it have to be so ugly? I'm sure there is a more pythonic way to do this in a one line of code. Please help me out.

+25  A: 

This is what list comprehensions are for:

numbers = [ int(x) for x in numbers ]
adamk
Thank you, that is what I was searching for :)
Silver Light
+12  A: 

In Python 2.x another approach is to use map:

numbers = map(int, numbers)

Note: in Python 3.x map returns a map object which you can convert to a list if you want:

numbers = list(map(int, numbers))
Mark Byers
In Python 3.x, `map` returns an iterator instead of a list, so it needs to be written as `list(map(int, numbers))` if a list is needed.
KennyTM
@KennyTM: Thanks. Updated. :)
Mark Byers
I think currently the list comprehension approach is a bit more favored.
extraneon
@extraneon: Yeah... or perhaps consider using a generator instead of a list, depending on what you will use it for. The advantage of a generator is that if you might not need to look at all elements then you won't have to waste time calculating them in advance.
Mark Byers
Last time I checked, `map` was still slightly faster than LC for `int`, but maybe the LC is easier for people to read
gnibbler
A: 

Another way,

for i, v in enumerate(numbers): numbers[i] = int(v)
Nick D
OP said *pythonic*
SilentGhost
no, he said "... more pythonic"
Nick D
+5  A: 

If you are intending on passing those integers to a function or method, consider this example:

sum(int(x) for x in numbers)

This construction is intentionally remarkably similar to list comprehensions mentioned by adamk. Without the square brackets, it's called a generator expression, and is a very memory efficient way of passing a list of arguments to a method. A good discussion is available here: http://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension

Tim McNamara
+2  A: 

just a point,

numbers = [int(x) for x in numbers]

this way is more natural for us, while

number = map(int, x)

is more fast.

Probably this will not matter in most cases

renatopp