Call int() function on every list element?


Question

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.

1
167
2/2/2017 9:21:36 PM

Accepted Answer

This is what list comprehensions are for:

numbers = [ int(x) for x in numbers ]
326
5/29/2018 4:43:13 PM

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))

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon