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.
Use the map() Function to Apply a Function to a List in Python. The map() function is used to apply a function to all elements of a specific iterable object like a list, tuple, and more. It returns a map type object which can be converted to a list afterward using the list() function.
Use int() function to Convert list to int in Python. This method with a list comprehension returns one integer value that combines all elements of the list.
Use the join() method of Python. First convert the list of integer into a list of strings( as join() works with strings only). Then, simply join them using join() method.
This is what list comprehensions are for:
numbers = [ int(x) for x in numbers ]
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))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With