How To Break Out Of Nested Loops In Python?
Solution 1:
A break
will only break out of the inner-most loop it's inside of. Your first example breaks from the outer loop, the second example only breaks out of the inner loop.
To break out of multiple loops you need use a variable to keep track of whether you're trying to exit and check it each time the parent loop occurs.
is_looping = True
for i in range(5): # outer loop
for x in range(4): # inner loop
if x == 2:
is_looping = False
break # break out of the inner loop
if not is_looping:
break # break out of outer loop
Solution 2:
In Python you can write an else
clause for a loop, which is executed when no break happens in the loop, or when the loop terminates naturally so to speak. Sometimes you can use it to break from multiple loops.
for i in some_range:
for j in some_other_range:
if need_break(i, j):
break
else:
continue
break # break happens in inner loop, break outer loop too.
Solution 3:
You can also do this with an exception, like this:
class ForLoopBreak(Exception):
pass
try:
for i in range(5):
for j in range(5):
print "({}, {})".format(i, j)
if i == 1 and j == 1:
# Break out of both for loops for this case
raise ForLoopBreak()
except ForLoopBreak:
pass
# Output
(0, 0)
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 0)
(1, 1)
Solution 4:
In the first code, the 'break' belongs to the outer 'for'. Hence the inner 'for' loop will be executed without any break, whereas, the outer 'for' will be executed only once.
In the second code, the 'break' belongs to the inner 'for'. So outer 'for' will be executed without any break, whereas, the inner 'for' will be executed only once in each iteration.
The difference is with respect to the indentation.
Post a Comment for "How To Break Out Of Nested Loops In Python?"