[Tutor] map vs. list comprehension
Michael Sparks
ms at cerenity.org
Tue Feb 14 23:00:16 CET 2006
On Tuesday 14 February 2006 20:57, Michael Broe wrote:
...
> 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]
>>> [ x**y for x,y in zip([2,2,2,2],[1,2,3,4]) ]
[2, 4, 8, 16]
To me this is clearer. (despite having written some substantial amount of code
in SML - a functional language where higher order functions are common)
Why ? Because it's easier to mentally break down into its parts for someone
less familiar with tools like map.
>>> zip([2,2,2,2],[1,2,3,4])
[(2, 1), (2, 2), (2, 3), (2, 4)]
>>> [ x**y for x,y in [(2, 1), (2, 2), (2, 3), (2, 4)] ]
[2, 4, 8, 16]
> Is there a way to do something like the following in a list
> comprehension?
>
> map(pow, [1, 7, 6, 2], [3, 8, 2, 5])
>>> [ x**y for x,y in zip([1,7,6,2],[3,8,2,5]) ]
[1, 5764801, 36, 32]
Regards,
Michael.
More information about the Tutor
mailing list