Is there a reason to prefer using map()
over list comprehension or vice versa? Is either of them generally more efficient or considered generally more pythonic
Actually, map
and list comprehensions behave quite differently in the Python 3 language. Take a look at the following Python 3 program:
def square(x):
return x*x
squares = map(square, [1, 2, 3])
print(list(squares))
print(list(squares))
You might expect it to print the line "[1, 4, 9]" twice, but instead it prints "[1, 4, 9]" followed by "[]". The first time you look at squares
it seems to behave as a sequence of three elements, but the second time as an empty one.
In the Python 2 language map
returns a plain old list, just like list comprehensions do in both languages. The crux is that the return value of map
in Python 3 (and imap
in Python 2) is not a list - it's an iterator!
The elements are consumed when you iterate over an iterator unlike when you iterate over a list. This is why squares
looks empty in the last print(list(squares))
line.
To summarize: