The Python Oracle

Call int() function on every list element?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Future Grid Looping

--

Chapters
00:00 Call Int() Function On Every List Element?
00:32 Accepted Answer Score 409
00:44 Answer 2 Score 160
01:01 Answer 3 Score 9
01:34 Answer 4 Score 28
01:51 Thank you

--

Full question
https://stackoverflow.com/questions/3371...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list #typeconversion #integer

#avk47



ACCEPTED ANSWER

Score 409


This is what list comprehensions are for:

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



ANSWER 2

Score 160


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



ANSWER 3

Score 28


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




ANSWER 4

Score 9


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