9

what is the difference between these sets of loops?

for i in range(0,5):
    print i,'i'
    for x in range(0,4):
        print x,'x'
    break

AND

for i in range(0,5):
    print i,'i'
    for x in range(0,4):
        print x,'x'
        break

what's the scope of break statement?

Soviut
  • 88,194
  • 49
  • 192
  • 260
Anonamous
  • 253
  • 2
  • 3
  • 14
  • Does this answer your question? [How to break out of multiple loops?](https://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops) – Josh Correia Nov 06 '20 at 19:54

6 Answers6

26

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
Soviut
  • 88,194
  • 49
  • 192
  • 260
19

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.
xiaofeng.li
  • 8,237
  • 2
  • 23
  • 30
5

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)
Chris McAfee
  • 104
  • 1
  • 4
  • 2
    You can use the built in [`StopIteration`](https://docs.python.org/3.12/library/exceptions.html#StopIteration) exception. – raratiru Jun 10 '22 at 18:11
1

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.

Srinivasan A
  • 51
  • 3
  • 12
1

The other answers already explain the difference between the two programs. I use private functions and return statement if I need to break out of nested loops. Here's a Python3 example:

matrix3d = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

def find():
  for (x, matrix) in enumerate(matrix3d):
    for (y, row) in enumerate(matrix):
      for (z, item) in enumerate(row):
        if item == 6:
          return (x, y, z)

pos = find()
Jatin Sanghvi
  • 1,928
  • 1
  • 22
  • 33
0

You can isolate the nested iterations in a generator, so that your processing proper is a single-level loop:

for x,y in ((x,y) for x in range(3) for y in range(2)):
    if condition(x,y):
        break

((x,y) for x in range(3) for y in range(2)) is a "generator expression" which is sufficient for simple cases, it can of course also be written as a generator function with a yield statement.

xenoid
  • 8,396
  • 3
  • 23
  • 49