Recap: Python’s map() function takes a function and an iterable—such as a list—as arguments. It then applies the function to each element in the iterable.
It returns a
p object. ?
But what if you don’t need a map object but a list?
Old: In Python 2.x this was easy: the
map() function simply returned a list rather than an iterable map object.
# Python 2.X print(map(lambda x: x+1, [1, 2, 3])) # Output: [2, 3, 4]
New: But if we try this in Python 3.x, the output is not as pretty:
print(map(lambda x: x+1, [1, 2, 3])) # Output: <map object at 0x0000013CE75DB4E0>
Let’s fix this!
To get Python’s built-in
map() function to return a list in Python 3.x, pass the map object into the
list() constructor to convert the iterable
map object into a list. For example, to convert the map object created by
map(lambda x: x+1, [1, 2, 3]) to a Python list, use
list(map(lambda x: x+1, [1, 2, 3])).
print(list(map(lambda x: x+1, [1, 2, 3]))) # Output: [2, 3, 4]
If you have any further question, feel free to join our email academy and ask!
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.