avatarYang Zhou

Summary

Python does not have built-in support for breaking out of nested loops, but there are several workarounds to achieve this.

Abstract

The article discusses five methods to break out of nested loops in Python, as it does not have built-in support for this operation. The methods include adding a flag variable, raising an exception, checking the same condition again, using the for-else syntax, and putting the nested loops into a function. The article also mentions the importance of avoiding nested loops if possible, by using helper functions like itertools.product.

Bullet points

  • Python does not have built-in support for breaking out of nested loops.
  • Five methods to break out of nested loops in Python:
    • Adding a flag variable
    • Raising an exception
    • Checking the same condition again
    • Using the for-else syntax
    • Putting the nested loops into a function
  • It is recommended to avoid nested loops if possible, by using helper functions like itertools.product.
  • The itertools.product function can be used to avoid nested loops, but it is only useful with finite inputs.

5 Ways To Break Out of Nested Loops in Python

Not as elegant as it should be

Photo by Johannes Plenio on Unsplash

We all know that Python is an elegant programming language. But everything has weaknesses. Sometimes Python is not as elegant as it should be.

For example, when we need to break out of nested loops as follows:

for a in list_a:
    for b in list_b:
        if condition(a,b):
            break

The break keyword can only help us break out of the inner-most loop. Can we directly break out of the two nested loops at once? Are there some built-in keywords or tricks for this in Python?

Unfortunately, there is no built-in support for this operation.

As an old saying goes, “comparison is the thief of joy”. Python can’t do this, but others can, such as the PHP:

foreach ($a_list as $a)
{
    foreach ($b_list as $b)
    {
        if (condition($a, $b))
        {
            break 2; //break out of 2 loops
        }
    }
}

In PHP, the break keyword accepts an optional number which determines how many nested loops are to be broken out of. The default value is 1, which means to break out of the inner-most loop.

It’s a very neat and clear solution. PHP is indeed more elegant here.

But it doesn’t mean we have to start to learn PHP now. Because Python is very flexible, we have many other ways to get the same result without grammatical support.

This article will introduce 5 methods to break out of nested loops in Python. And in the end, it mentions how to avoid the nested loops problem if it’s possible. Hopefully, you can regain confidence in Python after reading.

1. Add a Flag Variable

This is an effective solution. We define a variable and using it as a flag. Let’s see a simple example as follows:

As shown above, the break_out_flag variable is a great messenger to tell the program when it should break out of the outer loop.

It works well, but our code is a little untidy since we add a new variable to solve the simple problem. It’s not definitely necessary.

Let’s check out other choices.

2. Raise an Exception

If we can’t use the break keyword as expected. Why not implement the operation in another way? With the help of exception handling techniques in Python, we can break out of nested loops as follows:

As the above program showed, we can treat a “break” as an “exception” and throw it out of nested loops.

3. Check the Same Condition Again

Since one condition results in the breaking, checking the same condition in every loop is also a feasible solution. Like the following example:

The above way works, but it’s not a very good idea. At least not efficient. Because checking the same thing many times will waste lots of time.

4. Use the For-Else Syntax

Python has a special syntax: “for-else”. It’s not popular and someone even never knows it. Because everyone’s habit is to use the “else” after an “if”.

However, when it comes to breaking nested loops. This unconventional syntax can help.

The above code takes advantage of the “for-else” technique, because the code under the else statement will only execute when the inner loop finished without any breaking.

If you haven’t been familiar with the “for-else” syntax yet, check out the following code. It’s a “translation” of the “for-else” example.

In a word, this approach works, but we have to be familiar with the weird “if-else” syntax.

5. Put It Into a Function

If we put the nested loops into a function, the breaking problem becomes simple. Because we can use the return keyword instead of the break.

As shown above, this solution looks more elegant. There are no flags variables, no “try-except” or “for-else” syntax and no unnecessary condition checking.

Besides, “Turn Predicate Loops into Predicate Functions” is a good coding practice introduced by the team of LLVM compiler infrastructure.

Functions are very flexible in Python. We can define nested functions or closures easily. Therefore, if the nested loops will only be used once within another function, we can just define them in the outer function:

However, defining a nested function only for two for-loops is also seems not very elegant.

Final Thoughts: Avoid Nested Loops

If there are no elegant solutions to break out of nested loops, why not avoid writing nest loops? If it’s possible, we will smartly switch the hard problem into a easier problem.

By using some helper functions, we can indeed avoid nested loops:

As shown above, our previous example can avoid nested loops with the help of itertools.product function. It is a simple way to get Cartesian product of its input iterables.

Unfortunately, this way can’t avoid all nested loops. For example, if we need to handle infinite data streams in our loops, it can’t help.

Before product() runs, it completely consumes the input iterables, keeping pools of values in memory to generate the products. Accordingly, it is only useful with finite inputs.

But it’s still a good idea to avoid nested loops and improve readability of our programs.

Conclusion

We have at least five feasible ways to break out of nested loops in Python. None of them is as elegant as the approach of PHP, but at least we can implement this operation. Fortunately, we don’t have to use nested loops if we can convert them to a simpler loop with the help of the itertools.product function.

Thanks for reading. If you like it, please follow me and become a Medium member to enjoy more great articles about programming and technologies!

Relative articles:

Programming
Python
Coding
Technology
PHP
Recommended from ReadMedium