Silver Light Silver Light - 2 months ago 7
Python Question

Call int() function on every list element in Python

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.

Answer

This is what list comprehensions are for:

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