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

John La Rooy nospampls.jlr at doctor.com
Thu Feb 6 17:00:07 EST 2003


On Thu, 06 Feb 2003 06:15:06 GMT
jerf at compy.attbi.com wrote:

> 
> The question is whether the list comprehension is easier to read then the
> alternative for loop-based code. Even in your case, and with a bit of
> selective re-formatting that I would most assuredly use if I was actually
> writing that code,
> 
> [a+b+c for a in "hard"
>    for b in "to read" if b != 'e'
>      for c in "code" if c != 'o'
>        if " " not in a+b+c]
> 
> is still easier then
> 
> l = []
> for a in "hard":
>     for b in "to read":
>         if b != 'e':
>             for c in "code":
>                 if c != 'o':
>                     if " " not in a+b+c:
>                         l.append(a+b+c)
> 
> 

For excluding cases in a for loop, I often find it more readable to use 'continue' as
it helps keep the indenting under control - especially when the body of the loop gets
longer than a dozen lines. Comments help too ;o)

l = []
for a in "hard":
    for b in "to read":
        if b == 'e': 
            continue 

        for c in "code":
            if c == 'o':
                continue

            if " " not in a+b+c:
                l.append(a+b+c)


John






More information about the Python-list mailing list