Created
July 5, 2014 07:44
-
-
Save sullyj3/d6d4b994f0cf29b8ec6e to your computer and use it in GitHub Desktop.
suggestion for an additional for-loop structure.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
####################################### | |
# suggestion for an additional for-loop structure. | |
####################################### | |
for x in y while condition: | |
do_stuff() | |
# as syntax sugar for: | |
for x in y: | |
if condition: | |
do_stuff() | |
else: | |
break | |
# I want a way to loop through an iterable, but stop as soon as a condition | |
# becomes False. So, essentially I want a hybrid of a for and a while loop. | |
# Uses for stopping iteration once condition becomes False: | |
# - Useful for saving computation in cases where you know that, once the | |
# condition is False, it won't evaluate to True for any more of the elements in | |
# the iterable. | |
# - Especially important if the contents of the for block are | |
# computationally expensive. | |
# - Problem is compounded if you have a very long iterable. | |
# This could be accompanied by an additional list comprehension and generator | |
# expression structure: | |
l = [x for x in y while condition] | |
g = (x for x in y while condition) | |
# this syntax would be sugar for the more clunky: | |
l = [] | |
for x in y: | |
if condition: | |
l.append(x) | |
else: | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment