English (unofficial) translations of posts at kexue.fm
Source

[Memo] Several Approaches to Breaking Out of Multiple Loops in Python

Translated by DeepSeek V4 Pro. Translations can be inaccurate, please refer to the original post for important stuff.

Breaking Out of a Single Loop

Regardless of the programming language, there is often a need to break out of a loop. For example, during an enumeration, you might want to terminate as soon as a condition is met. Breaking out of a single loop is very straightforward:

for i in range(10):
    if i > 5:
        print i
        break

However, we sometimes need to break out of multiple nested loops. Since break can only exit the current level of the loop, consider the following:

for i in range(10):
    for j in range(10):
        if i+j > 5:
            print i,j
            break

This code does not stop as soon as it finds a single pair where i+j > 5. Instead, it will find 10 such pairs because the break only exits the for j in range(10) loop. So, how can we break out of multiple levels? I am recording a few methods here for future reference.

Breaking Out of Multiple Loops

In fact, Python’s standard syntax does not natively support breaking out of multiple loops. Therefore, we must rely on certain techniques. The general ideas include: wrapping the logic in a function, using Cartesian products, or utilizing exception handling.

Encapsulating as a Function

In Python, a function stops execution as soon as it reaches a return statement. We can leverage this characteristic by wrapping the logic into a function to terminate multiple loops:

def work():
    for i in range(10):
        for j in range(10):
            if i+j > 5:
                return i,j

print work()

Using Cartesian Product

The idea behind this method is that since we can break out of a single loop, we can rewrite multiple loops as a single loop. This can be achieved using the product function from the itertools module to create a Cartesian product:

from itertools import product

for i,j in product(range(10), range(10)):
    if i+j > 5:
        print i,j
        break

Using Exception Handling

The Cartesian product method is clever and concise, but it only works when the sets for each loop are independent. If a nested loop depends on the value of the outer loop, this trick cannot be used. In such cases, you can use the first method (wrapping it in a function) or utilize exception handling. This approach relies on the principle that an error will terminate execution unless caught, so we "disguise" a termination signal as a custom exception.

class Found(Exception):
    pass

try:
    for i in range(10):
        for j in range(i): # The second loop depends on the first
            if i + j > 5:
                raise Found
except Found:
    print i, j

When reposting, please include the original article address:
https://kexue.fm/archives/4159

For more detailed information regarding reposting, please refer to:
"Scientific Space FAQ"