
On Thu, Nov 20, 2014, at 10:49, MRAB wrote:
I can see the problem with 'while': if there are multiple 'for' parts, they are equivalent to nested 'for' loops, so you might assume that a 'while' part would also be equivalent to a nested 'while' loop, whereas it would, in fact, be controlling the preceding 'for' part.
In other words, it would be:
for x in range(10) while x < 5: ....
but could be seen as:
for x in range(10): while x < 5: ....
I've always thought of comprehensions as a sort of "inside-out" loop, due to the value at the beginning: (f(a) for a in range) is roughly equivalent to for a in range: yield f(a).
Due to this, I was actually somewhat surprised to find that multiple for clauses don't work as if they were nested inside-out loops
[(a, b) for a in range(3) for b in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
[[(a, b) for a in range(3)] for b in range(3)]
[[(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)]]
I think people trying to use "while" for this are coming from an english-grammar point of view.