Call int() function on every list element?

StackOverflow

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 rating: 392

This is what list comprehensions are for:

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

Answer rating: 145

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




Get Solution for free from DataCamp guru