How to break outer ones of nested loops in Python?

alibahaari

Ali Bahaari

Posted on November 12, 2021

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

BOOM! It prints number four only 1 time.

Use and enjoy!

💖 💪 🙅 🚩
alibahaari
Ali Bahaari

Posted on November 12, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related