Exit Nested Loops in Python

Using a Boolean Flag:

done = False
for x in xs:
    for y in ys:
        if bad:
            done = True
            break

    if done:
        break

This method uses a done flag to indicate when the loop should exit. It’s simple and clear, which is great when readability is a priority. However, it does require manually managing the flag, which might feel a bit verbose if you’re dealing with a lot of loops.