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 ma
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>
Bah!
Let’s fix this!
Solution: list(map(...))
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!