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.
This question is related to
python
list
type-conversion
integer
Another way to make it in Python 3:
numbers = [*map(int, numbers)]
Another way,
for i, v in enumerate(numbers): numbers[i] = int(v)
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: Generator Expressions vs. List Comprehension
Thought I'd consolidate the answers and show some timeit
results.
Python 2 sucks pretty bad at this, but map
is a bit faster than comprehension.
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> setup = """import random
random.seed(10)
l = [str(random.randint(0, 99)) for i in range(100)]"""
>>> timeit.timeit('[int(v) for v in l]', setup)
116.25092001434314
>>> timeit.timeit('map(int, l)', setup)
106.66044823117454
Python 3 is over 4x faster by itself, but converting the map
generator object to a list is still faster than comprehension, and creating the list by unpacking the map
generator (thanks Artem!) is slightly faster still.
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> setup = """import random
random.seed(10)
l = [str(random.randint(0, 99)) for i in range(100)]"""
>>> timeit.timeit('[int(v) for v in l]', setup)
25.133059591551955
>>> timeit.timeit('list(map(int, l))', setup)
19.705547827217515
>>> timeit.timeit('[*map(int, l)]', setup)
19.45838406513076
Note: In Python 3, 4 elements seems to be the crossover point (3 in Python 2) where comprehension is slightly faster, though unpacking the generator is still faster than either for lists with more than 1 element.
just a point,
numbers = [int(x) for x in numbers]
the list comprehension is more natural, while
numbers = map(int, numbers)
is faster.
Probably this will not matter in most cases
Useful read: LP vs map
Source: Stackoverflow.com