python – How to break out of multiple loops?

python – How to break out of multiple loops?

My first instinct would be to refactor the nested loop into a function and use return to break out.

Heres another approach that is short. The disadvantage is that you can only break the outer loop, but sometimes its exactly what you want.

for a in xrange(10):
    for b in xrange(20):
        if something(a, b):
            # Break the inner loop...
        # Continue if the inner loop wasnt broken.
    # Inner loop was broken, break the outer.

This uses the for / else construct explained at: Why does python use else after for and while loops?

Key insight: It only seems as if the outer loop always breaks. But if the inner loop doesnt break, the outer loop wont either.

The continue statement is the magic here. Its in the for-else clause. By definition that happens if theres no inner break. In that situation continue neatly circumvents the outer break.

python – How to break out of multiple loops?

PEP 3136 proposes labeled break/continue. Guido rejected it because code so complicated to require this feature is very rare. The PEP does mention some workarounds, though (such as the exception technique), while Guido feels refactoring to use return will be simpler in most cases.

Leave a Reply

Your email address will not be published. Required fields are marked *