Counting nested loop iterations

Joel Hedlund joel.hedlund at gmail.com
Fri Mar 17 07:50:56 EST 2006


> for index, color in enumerate(color
>                               for animal in zoo
>                               for color in animal):
>     # the something more goes here.
>     pass

I've been thinking about these nested generator expressions and list 
comprehensions. How come we write:

a for b in c for a in b

instead of

a for a in b for b in c

More detailed example follows below.

I feel the latter variant is more intuitive. Could anyone please explain the 
fault of my logic or explain how I should be thinking about this? Or point me 
to somewhere where I can read up on this?

Cheers,
Joel Hedlund



More detailed example:
 >>> c = [[1,4,8],[2,5,7]]
 >>> [a for b in c for a in b]
[1, 4, 8, 2, 5, 7]
 >>> del a,b,c
 >>> c = [[1,4,8],[2,5,7]]
 >>> [a for a in b for b in c]

Traceback (most recent call last):
   File "<pyshell#30>", line 1, in -toplevel-
     [a for a in b for b in c]
NameError: name 'b' is not defined






More information about the Python-list mailing list