possibly trivial newbie list/array question

Mark J maj64 at hotmail.com
Thu Aug 23 23:21:31 EDT 2001


Hans Nowak <hnowak at cuci.nl> wrote in message news:<mailman.998573411.21163.python-list at python.org>...
> >===== 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'.)

But how about the straightforward, obvious, syntactically consistent,
and just as fast (yes, I did a test):

l = []
for x in range(10):
    if x % 2:
        l += [x]

List comprehensions do seem a bit of a syntactic "hair" just to save
one name assignment.  If you're doing it to just save a few lines of
code, that's easily done too without adding more inconsistent syntax:

l = []; for x in range(10): if x % 2: l += [x]

In what cases are list comprehensions significantly better?

Thanks,

Mark



More information about the Python-list mailing list