When is List Comprehension inappropriate?

Alex Martelli aleax at mac.com
Tue Mar 20 16:11:26 CET 2007


Aahz <aahz at pythoncraft.com> wrote:

> In article <1hv8wz8.19mj0kb1k9m2m8N%aleax at mac.com>,
> Alex Martelli <aleax at mac.com> wrote:
> >
> >list(iterimage(etc etc))
> >
> >is surely a better way to express identical semantics.  More generally,
> >[x for x in whatever] (whether x is a single name or gets peculiarly
> >unpacked and repacked like here) is a good example of inappropriate LC,
> >to get back to the question in the subject: list(whatever) is the "one
> >obvious way" to perform the same task.
> 
> Except of course, when it's
> 
> [x for x in whatever if x]
> 
> I'm exceedingly fond of replacing filter() with listcomps.  They're so
> much more readable and often faster.

Sure, if there are other clauses in the LC (be they for or if ones) you
can't just call list(...) -- and I do entirely agree that filter can be
put out to pasture.  Similarly, you need the LC if you're performing
some processing on the items -- for example, if you have an iterator
yielding pairs,
  [(y,x) for x,y in whatever]
you do need the unpacking and repacking to achieve this swapping of
items within each pair -- what I was pointing out was re the simpler and
most common case:
  [(x,y) for x,y in whatever]
no processing needed, no if clauses, etc, and thus better expressed as
  list(whatever)


Alex



More information about the Python-list mailing list