Exit Nested Loops in Python

Building on Jacqueline’s idea, another option is to use else and continue:

for x in xs:
    for y in ys:
        if bad:
            break
    else:
        continue

    break

This approach leverages Python’s else clause for loops, which can make the intent clearer by bundling the logic together. It avoids the explicit done flag, which simplifies the code. Still, the keyword usage here might not be as familiar to everyone, so make sure to document your intent if you’re working in a team.

By the way, this is one of those moments where Python’s little extras, like the else on a loop, shine!