How To Exit From A Nested Loop In Python

Nested loops are commonly used in Python to carry out repeated actions on multidimensional data, such as matrices.

However, there might be situations where one would want to exit from multiple loops at once given a certain condition, and Python doesn’t come with a straightforward mechanism to break out, like the break statement or regular loops. This tutorial will demonstrate some techniques to exit from a nested loop in Python.

1. Using Exceptions

One way to exit a nested loop is by using exceptions. Here’s how you can use exceptions to break out of nested loops:

  1. Define a custom exception class that inherits from the base Exception class.
  2. Inside the nested loop, raise the custom exception when the desired condition is met.
  3. Enclose the nested loop inside a try block and handle the custom exception using an except block.

For example, consider the following nested loop:

To break out of both loops when i == 5 and j == 5, use the following approach:

2. Using Functions

Another approach to exit a nested loop is by wrapping the nested loop in a function and using the return statement. Here’s the process:

  1. Create a function that contains the nested loop.
  2. Inside the nested loop, call the return statement when the desired condition is met.
  3. Invoke the function in your code.

Using the same example as before, you can break out of both loops with the following code:

Full Code and Output

Exception Method:

Output:

0 0
0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8
0 9
1 0
...
5 5

Function Method:

Output:

0 0
0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8
0 9
1 0
...
5 5

Conclusion

In this tutorial, we have explored two methods to break out nested loops in Python using exceptions and functions.

While the exception method provides a more “Pythonic” approach, the function method can be easier to read and understand for those who are new to Python. Choose the method that works best for your specific use case and coding style.