list comprehension question

Emile van Sebille emile at fenx.com
Fri May 1 12:01:05 EDT 2009


On 5/1/2009 7:31 AM J Kenneth King said...
> Chris Rebert <clp2 at rebertia.com> writes:
>> b = []
>> for pair in a:
>>     for item in pair:
>>         b.append(item)
> 
> This is much more clear than a nested comprehension.
> 
> I love comprehensions, but abusing them can lead to really dense and
> difficult to read code.

I disagree on dense and difficult, although I'll leave open the question 
of abuse.

b = [ item for pair in a for item in pair ]

This is exactly the code above expressed in comprehension form.

It's worth knowing that a list comprehension is structured identically 
to the equivalent for loop.  So it really is neither more dense nor more 
difficult to read.  Further, you can tell immediately from the start of 
the list comprehension what you've got -- in this case a list of item(s).

Here with some slight changes...

 >>> a = [(1, 2), (3, 4, 7), (5, 6)]
 >>> [ item for j in a if len(j)==2 for item in j if item % 2 ]
[1, 5]

...opposed to...

 >>> for j in a:
...     if len(j)==2:
...         for item in j:
...             if item % 2:
...                 b.append(item)
...
 >>> b
[1, 5]
 >>>

YMMV,

Emile





More information about the Python-list mailing list