possibly trivial newbie list/array question

Hans Nowak hnowak at cuci.nl
Thu Aug 23 09:39:30 EDT 2001


>===== Original Message From Paul Rubin <phr-n2001 at nightsong.com> =====
>Can you tell me the actual purpose of list comprehension?
>
>        [f(x) for x in a]
>
>just seems like confusing syntactic hair that's otherwise equivalent
>to, though as we've seen sometimes slower than,
>
>        map(lambda x: f(x), a).
>
>Am I missing something?  Unless there's more to it than I see (which
>is quite possible), I don't understand why this feature made it into
>the language.

Interesting... one of the reasons to add this was because it was thought to be 
more readable than the functional stuff (map, filter, lambda)... :) Sometimes 
it is. Compare:

>>> [x*2+1 for x in range(10) if x % 2]
[3, 7, 11, 15, 19]
>>> map(lambda x: x*2+1, filter(lambda x: x%2, range(10)))
[3, 7, 11, 15, 19]

I think the first one is clearer, but that's largely a matter of preference. 
Sometimes I use a listcomp, sometimes a simple map will do. I think that this 
feature was added to provide an alternative to lambda/map and friends, which 
encourage obfuscation. (If this was the case, it's incomplete, methinx... 
there's no alternative for 'reduce'.)

Regards,

--Hans Nowak





More information about the Python-list mailing list