Call int() function on every list element?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Luau
--
Chapters
00:00 Question
00:45 Accepted answer (Score 403)
00:59 Answer 2 (Score 159)
01:21 Answer 3 (Score 27)
01:45 Answer 4 (Score 9)
02:20 Thank you
--
Full question
https://stackoverflow.com/questions/3371...
Accepted answer links:
[list comprehensions]: https://docs.python.org/3/tutorial/datas...
Answer 2 links:
[map]: https://docs.python.org/2/library/functi...
[map]: https://docs.python.org/3/library/functi...
Answer 3 links:
[LP vs map]: https://stackoverflow.com/questions/1247...
Answer 4 links:
[Generator Expressions vs. List Comprehension]: https://stackoverflow.com/questions/4778...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #typeconversion #integer
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Luau
--
Chapters
00:00 Question
00:45 Accepted answer (Score 403)
00:59 Answer 2 (Score 159)
01:21 Answer 3 (Score 27)
01:45 Answer 4 (Score 9)
02:20 Thank you
--
Full question
https://stackoverflow.com/questions/3371...
Accepted answer links:
[list comprehensions]: https://docs.python.org/3/tutorial/datas...
Answer 2 links:
[map]: https://docs.python.org/2/library/functi...
[map]: https://docs.python.org/3/library/functi...
Answer 3 links:
[LP vs map]: https://stackoverflow.com/questions/1247...
Answer 4 links:
[Generator Expressions vs. List Comprehension]: https://stackoverflow.com/questions/4778...
--
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