A few nested 'for' loops, continue the next iteration of the outer loop if the condition inside the inner loop is true

I know this is terribly inefficient and ugly code, but if I have three for loops nested inside each other, for example:

 for x in range(0, 10): for y in range(x+1, 11): for z in range(y+1, 11): if ... 

I want to break the two inner loops and continue the next iteration of the outer loop if the if true. It can be done?

+5
source share
4 answers

Check some variables after the end of each cycle:

 for x in range(0, 10): for y in range(x+1, 11): for z in range(y+1, 11): if condition: variable = True break #... if variable: break; #... 
+4
source

Another option is to use exceptions instead of state variables:

 class BreakException(Exception): pass for x in range(0, 10): try: for y in range(x+1, 11): for z in range(y+1, 11): if True: raise BreakException except BreakException: pass 

I suggest that this can be especially useful if you jump out of more than two inner loops.

+2
source
 n = False for x in range(0,10): if n == True: print(x,y,z) for y in range(x+1, 11): if n == True: break for z in range(y+1, 11): if z == 5: n = True break (1, 2, 5) (2, 2, 5) (3, 3, 5) (4, 4, 5) (5, 5, 5) (6, 6, 5) (7, 7, 5) (8, 8, 5) (9, 9, 5) 
+1
source

A possible solution is to combine the two inner loops into one (which can be completed with break ):

 import itertools for x in range(10): for y, z in itertools.combinations(range(x+1, 11), 2): if condition: break 
0
source

Source: https://habr.com/ru/post/1240359/


All Articles