List comprehensions' ugliness (Was: Re: How to explain exactly what "def" does?)

Hans Nowak wurmy at
Wed Feb 5 22:00:25 CET 2003

Gerrit Holl wrote:

> So, when exactly is a list comprehension ugly? I use them a lot in
> places where I used to use filter. For example:
> filter(foo, i) --> [i for i in l if foo(i)]
> Is this abuse?
> What is the correct use for list comprehensions and what isn't?

Besides readability, which varies per situation, I suppose that a list comp can 
be called "ugly" or even "abuse" if it's used for something it wasn't really 
meant for.  Your example is alright, although some prefer the filter() 
function.  Something more dubious is this:

   [mylist.append(z) for z in otherlist]

The point of list comprehensions is to return a list, and the example above 
doesn't do anything with that list.  It's better written as

   for z in otherlist:

I'm sure there are better (worse?) examples of list comp abuse.


Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter::

More information about the Python-list mailing list