Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call int() function on every list element?

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.

like image 809
Silver Light Avatar asked Jul 30 '10 12:07

Silver Light


People also ask

How do you apply a function to every item in a list?

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.

How do you int each element in a list?

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.

Can you join a list of ints?

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.


3 Answers

This is what list comprehensions are for:

numbers = [ int(x) for x in numbers ] 
like image 135
adamk Avatar answered Sep 22 '22 06:09

adamk


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)) 
like image 20
Mark Byers Avatar answered Sep 26 '22 06:09

Mark Byers


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

like image 32
renatopp Avatar answered Sep 22 '22 06:09

renatopp