Ali Bahaari

Posted on

# How to break outer ones of nested loops in Python?

You may have faced something weird in Python!
Consider you would use two nested loops. Just use `break` keyword in the most internal one. What happens? Only the internal one would be broken and stop working. What about the others? Well, Python doesn't have any elegant way for doing this. I'll tell you how to deal with it.

## Example

Run the code below:

``````for i in range(10):
for j in range(10):
if j == 4:
print(j)
break
``````

You would see number four 10 times. But...
Sometimes the inner loops depend on outer ones. Therefore you need to stop outer ones when conditions are provided in inner ones.

## Solving the Problem

The most easy way for solving the problem is using flags.

Check the code below:

``````loop_breaker = False

for i in range(10):
if loop_breaker:
break

for j in range(10):
if j == 4:
print(j)

loop_breaker = True

break
``````

BOOM! It prints number four only 1 time.

Use and enjoy!

xtofl

Most of the time when I encounter a nested loop, it can be removed completely by clarifying the intent of the author: "finding" a value that satisfies a predicate in the carthesian product of some ranges.

``````found = next(
j for _, j in itertools.product(range(10), range(10))
if j == 4
)
``````

This way, breaking out of the loop does not break the code reader's attention. (It may be broken by having to look up what `itertools.product` is :))

Ali Bahaari

Thanks!