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

jerf at compy.attbi.com jerf at compy.attbi.com
Thu Feb 6 01:15:06 EST 2003


On Wed, 05 Feb 2003 14:40:30 -0800, Dave Brueck wrote:

> On Wed, 5 Feb 2003, Hans Nowak wrote:
> 
>> I'm sure there are better (worse?) examples of list comp abuse.
> 
>>>> [a+b+c for a in "hard" for b in "to read" if b != 'e' for c in "code"
> if c!='o' if len((a+b+c).split()) == 1]
> 
> ['htc', 'htd', 'hte', 'hoc', 'hod', 'hoe', 'hrc', 'hrd', 'hre', 'hac',
> 'had', 'hae', 'hdc', 'hdd', 'hde', 'atc', 'atd', 'ate', 'aoc', 'aod',
> 'aoe', 'arc', 'ard', 'are', 'aac', 'aad', 'aae', 'adc', 'add', 'ade',
> 'rtc', 'rtd', 'rte', 'roc', 'rod', 'roe', 'rrc', 'rrd', 'rre', 'rac',
> 'rad', 'rae', 'rdc', 'rdd', 'rde', 'dtc', 'dtd', 'dte', 'doc', 'dod',
> 'doe', 'drc', 'drd', 'dre', 'dac', 'dad', 'dae', 'ddc', 'ddd', 'dde']
> 
> -Dave

The point is not whether a given list comprehension is "hard to read"...
hard to read code in a language like Python is firmly the responsibility
of the programmer. 

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)






More information about the Python-list mailing list