Call int() function on every list element?

Viewed 319489

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.

8 Answers

Another way to make it in Python 3:

numbers = [*map(int, numbers)]

However ideally you may be happy just with map, as it is returning an iterator:

numbers = map(int, numbers)

It may also be worth noting that NumPy will do this on the fly when creating an array:

import numpy as np

numbers = ['1', '5', '10', '8']
numbers = np.array(numbers,
                   dtype=int)
numbers
array([ 1,  5, 10,  8])
Related