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

Alex Martelli aleax at aleax.it
Thu Feb 6 01:25:41 CET 2003


Hans Nowak wrote:
   ...
>    [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)

mylist.extend(otherlist) is better.


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

Sure, such as faking assign-and-test:

while [x for x in [<expression>] if x]:
    process(x)

since you cannot do:

while x=<expression>:
    process(x)

I think this is the iffiest/ugliest of the possibly-handy uses of LCs --
it's not very clear AND relies on the sad fact that the bindings in
a LCs' for clauses "leak" to the surrounding scope (a LC doesn't
have its own scope "nested" in the surrounding one).


Alex





More information about the Python-list mailing list