Turns out, as @Paul McGuire noted, that it had been proposed in PEP 3142 and got rejected by Guido:
I didn't know there was a PEP for that. I hereby reject it. No point wasting more time on it.
He doesn't give explanations, though. In the mailing list, some of the points against it are:
- "[comprehension are] a carefully designed 1 to 1 transformation between multiple nested statements and a single expression. But this proposal ignores and breaks that. (here)." That is, the
while
keyword does not correspond to awhile
in the explicit loop - it is only abreak
there. - "It makes Python harder to learn because it adds one more thing to learn." (cited here)
- It adds another difference between generator expressions and list-comprehension. Seems like adding this syntax to list comprehension too is absolutely out of the question.
I think one basic difference from the usual list comprehension is that while
is inherently imperative, not declarative. It depends and dictates an order of execution, which is not guaranteed by the language (AFAIK). I guess this is the reason it is not included in Haskell's comprehensions, from which Python stole the idea.
Of course, generator expressions do have direction, but their elements may be precomputed - again, AFAIK. The PEP mentioned did propose it only for generator expressions - which makes some sense.
Of course, Python is an imperative language anyway, but it will raise problems.
What about choosing out of a non-ordered collection?
[x for x in {1,2,3} while x!=2]
You don't have it in simple for
loops too, but that's something you can't enforce by the language. takewhile
answers this question, but it is an arbitrary answer.
One last point, note that for consistency you will want support for dropwhile
. something like
[x for x in my_list from x != 'potato']
Which is even less related to the equivalent for
construct, and this time it is not possibly short circuit if my_list
is just an iterable.