How to stop one or multiple for loop(s)

Use break and continue to do this. Breaking nested loops can be done in Python using the following:

for a in range(...):
   for b in range(..):
      if some condition:
         # break the inner loop
      # will be called if the previous loop did not end with a `break` 
   # but here we end up right after breaking the inner loop, so we can
   # simply break the outer loop as well

Another way is to wrap everything in a function and use return to escape from the loop.

Leave a Comment