[Tutor] map vs. list comprehension

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Feb 14 23:10:03 CET 2006



> I read somewhere that the function 'map' might one day be deprecated in
> favor of list comprehensions.
>
> But I can't see a way to do this in a list comprehension:
>
>  >>> map (pow, [2, 2, 2, 2], [1, 2, 3, 4])
> [2, 4, 8, 16]


Hi Michael,

If my hands were forcibly tied to avoid map(), I'd try something like:

########################################################
[pow(base, exponent)
 for (base, exponent) in zip([2, 2, 2, 2], [1, 2, 3, 4])]
##########################################################


But even if map() no longer stays as a builtin, we can always get it back:

######
>>> def mymap(f, *args):
...     return [f(*elts) for elts in zip(*args)]
...
>>> def square(x):
...     return x*x
...
>>> mymap(square, range(20))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256,
 289, 324, 361]
######

(You might notice that mymap() looks very analogous to what we've done in
the pow() list comprehension above.)


So I would not be too concerned about what happens in Python 3000: if
things change, we can route around damage.


Best of wishes to you!



More information about the Tutor mailing list