Allowing breaks in generator expressions by overloading the while keyword
20 Feb
2014
20 Feb
'14
9:13 p.m.
Sometimes you need to build a list in a loop, but break from the loop if some condition is met, keeping the list up to that point. This is so common it doesn't really need an example. Trying to shoehorn the break keyword in to the generator expression syntax doesn't look pretty, unless you add `and break if expr` to the end, but that has its own issues. Besides, overloading `while` is much cuter... ls = [ expr for name in iterable while expr ] ls = [ expr for name in iterable if expr while expr ] ls = [ expr for name in iterable if expr else expr while expr ] With regular generator expressions, it gives you a kind of base case, which may assist with showing off.
3705
Age (days ago)
3708
Last active (days ago)
35 comments
16 participants
participants (16)
-
Andrew Barnert
-
Antoine Pitrou
-
Carl Smith
-
Chris Angelico
-
David Mertz
-
Greg Ewing
-
M.-A. Lemburg
-
Masklinn
-
Mathias Panzenböck
-
MRAB
-
Nick Coghlan
-
Oscar Benjamin
-
Ryan Gonzalez
-
Stephen J. Turnbull
-
Steven D'Aprano
-
אלעזר