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
map
and filter
instead of list comprehensions.An objective reason why you should prefer them even though they're not "Pythonic" is this:
They require functions/lambdas as arguments, which introduce a new scope.
I've gotten bitten by this more than once:
for x, y in somePoints:
# (several lines of code here)
squared = [x ** 2 for x in numbers]
# Oops, x was silently overwritten!
but if instead I had said:
for x, y in somePoints:
# (several lines of code here)
squared = map(lambda x: x ** 2, numbers)
then everything would've been fine.
You could say I was being silly for using the same variable name in the same scope.
I wasn't. The code was fine originally -- the two x
s weren't in the same scope.
It was only after I moved the inner block to a different section of the code that the problem came up (read: problem during maintenance, not development), and I didn't expect it.
Yes, if you never make this mistake then list comprehensions are more elegant.
But from personal experience (and from seeing others make the same mistake) I've seen it happen enough times that I think it's not worth the pain you have to go through when these bugs creep into your code.
Use map
and filter
. They prevent subtle hard-to-diagnose scope-related bugs.
Don't forget to consider using imap
and ifilter
(in itertools
) if they are appropriate for your situation!