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

Hans Nowak wurmy at earthlink.net
Wed Feb 5 16:00:25 EST 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:
       mylist.append(z)

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

Cheers,

-- 
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/
Kaa:: http://www.awaretek.com/nowak/kaa.html
Soon: http://zephyrfalcon.org/





More information about the Python-list mailing list