On Tue, Jan 29, 2013 at 1:32 AM, Shane Green email@example.com wrote:
Isn't "while" kind just the "if" of a looping construct?
Would [n for n in range(1,1000) while n < 400] == [n for n in range(1,1000) if n < 400]?
I guess your kind of looking for an "else break" feature to exit the list comprehension before evaluating all the input values. Wouldn't that complete the "while()" functionality?
In the specific case given, they'll produce the same result, but there are two key differences:
1) If the condition becomes true again later in the original iterable, the 'if' will pick up those entries, but the 'while' won't; and 2) The 'while' version will not consume more than the one result that failed to pass the condition.
I daresay it would be faster and maybe cleaner to implement this with a language feature rather than itertools.takewhile, but list comprehensions can get unwieldy too; is there sufficient call for this to justify the syntax?