How can I exit out of two loops in Python? I have the following nested loops:
for row in b:
for drug in drug_input:
for brand in brand_names[drug]:
From the third loop, how can I exit the current loop and move to the next iteration of for row in b:
?
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.
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!
If you want a more unique approach, consider using a try-except
block with a break
mechanism:
try:
for x in xs:
for y in ys:
if bad:
raise Exception("Breaking out")
except Exception:
pass
Here, raise
is used to break out of both loops in a controlled way. While this might seem unconventional, it can be very powerful in scenarios where additional error handling is required. It’s also clear in intent—‘breaking out’ is quite literally what you’re doing!
That said, I’d only recommend this method if you’re already using exceptions in your workflow. If not, Jacqueline’s or Charity’s approaches are probably more Pythonic and maintainable.
Ultimately, choosing the right method depends on your code’s context and complexity. 