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

holger krekel pyth at devel.trillke.net
Wed Feb 5 12:24:15 EST 2003


Gerrit Holl wrote:
> Greg Ewing (using news.cis.dfn.de) schreef op dinsdag  4 februari om 00:32:39 +0000:
> > List comps themselves aren't ugly, but abusing them
> > for things like that certainly is! (And probably
> > gives them a bad name.)
> 
> 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)]

you mean

    filter(foo, l)

To some of us the filter version reads much better.
It actually tells exactly what is happening: 
the 'foo' function filters out matching elements.

whereas the list comprehension

    [i for i in l if foo(i)]

needs to be interpreted almost token by token. 

> What is the correct use for list comprehensions and what isn't?

It's nice to use list comprehensions when you would otherwise
need to use lambda constructs (anonymous functions). consider

    filter(lambda x: x.name.startswith('emil'), l)

and 

    [x for x in l if x.name.startswith('emil')]

Here the lambda-construct starts to get more dubious because
you also have to 'parse' it by hand.  List comprehensions
are sometimes more legible than those lambda-constructs.

Of course friends of filter might argue that with

    class hasprefix(str):
        def __call__(self, arg):
            return arg.startswith(self)

the filter version

    filter(hasprefix('emil'), l)

again reads better.  Probably this depends mostly on your
programming background. If you like passing function 
objects around then you might prefer filter/map/reduce
constructs sometimes. 

regards,

    holger





More information about the Python-list mailing list