Counting nested loop iterations
Fredrik Lundh
fredrik at pythonware.com
Fri Mar 17 09:02:15 EST 2006
Joel Hedlund wrote:
> 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?
out = [a for b in c for a in b]
can be written
out = [a
for b in c
for a in b]
which is equivalent to
out = []
for b in c:
for a in b:
out.append(a)
in other words, a list comprehension works exactly like an ordinary for
loop, except that the important thing (the expression) is moved to the
beginning of the statement.
</F>
More information about the Python-list
mailing list