Ezio Melotti <[email protected]> added the comment:
This section could be clearer imho.
First of all there's nothing special about "nested" list comprehensions. In
[expr for elem in seq], expr might be any expression -- including a listcomp.
As with any other expression, the nested listcomp will be executed for each
elem in seq, so there's really nothing new to explain here.
The "reading order" is always from left to right, with the expression at the
end:
[expr for x in seq1 for y in seq2 for z in seq3]
^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^
last first second third...
So I agree that "To avoid apprehension when nesting list comprehensions, read
from right to left." is a bit confusing/wrongish (is actually correct for
listcomp with only a single for, but that's just a coincidence and it's not
related to nested listcomps).
The previous section could also be a little clearer, showing the classic
example:
squares = [x**2 for x in range(10)]
and saying that it's equivalent to
squares = []
for x in range(10):
squares.append(x**2)
and, similarly, that
combs = [(c1, c2) for c1 in 'abc' for c2 in 'xyz']
is equivalent to
combs = []
for c1 in 'abc':
for c2 in 'xyz':
combs.append((c1, c2))
Showing the "reading direction" with these two equivalents and saying that
nested listcomps follow the same rule (because there's nothing different about
them), should be enough to make things clear.
In addition, the example with the matrix shouldn't use print in the "expanded"
version, but rather something like:
res = []
for i in [0, 1, 2]:
res.append([row[i] for row in mat])
print res
----------
nosy: +ezio.melotti
stage: -> needs patch
versions: +Python 3.2, Python 3.3 -Python 2.6
_______________________________________
Python tracker <[email protected]>
<http://bugs.python.org/issue13549>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com