possibly trivial newbie list/array question

Steve Holden sholden at holdenweb.com
Fri Aug 24 00:05:50 EDT 2001


"Mark J" <maj64 at hotmail.com> wrote in message
news:a0567c6b.0108231921.76359385 at posting.google.com...
> 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?
>

>>> l = []; for x in range(10): if x % 2: l += [x]
Traceback (  File "<interactive input>", line 1
    l = []; for x in range(10): if x % 2: l += [x]
              ^
SyntaxError: invalid syntax

When they don't give syntax errors?

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list