DEV Community

Bas codes
Bas codes

Posted on

Breaking out a nested loop in Python

Let's have a look at nested loops in Python!

How can we break out of both loops with code on the inner loop?

for i in range(1, 4):
    for j in range(1, 4):
        if j == 2:
            break # But please also break the outer loop!
        print(i, j)
Enter fullscreen mode Exit fullscreen mode

else block

One solution with an πšŽπš•πšœπšŽ block:

If we are not stopped by any πš‹πš›πšŽπšŠπš” in the inner loop (that's what πšŽπš•πšœπšŽ means), the rest of the outer loop will not be executed (πšŒπš˜πš—πšπš’πš—πšžπšŽ)
If we are, the outer loop is terminated (πš‹πš›πšŽπšŠπš”), too

for i in range(1, 4):
    for j in range(1, 4):
        print(i, j)
        if j == 2:
            break
    else:
        continue
    break
Enter fullscreen mode Exit fullscreen mode

itertools

That doesn't look very pretty and anyone who sees that code has to think twice about it.

So, here is a more elegant solution using πš’πšπšŽπš›πšπš˜πš˜πš•πšœ

The πš™πš›πš˜πšπšžπšŒπš method boils down our two loops into one:

import itertools
for i, j in itertools.product(range(1, 4), range(1, 4)):
    print(i, j)
    if j == 2:
        break
Enter fullscreen mode Exit fullscreen mode

A custom generator function

Using a generator function, we can replicate the behaviour of πš’πšπšŽπš›πšπš˜πš˜πš•πšœ' πš™πš›πš˜πšπšžπšŒπš method.

The πš’πš’πšŽπš•πš keyword makes the result of your function a generator.

def generator(outer_iterable, inner_iterable):
    for i in outer_iterable:
        for j in inner_iterable:
            yield (i, j)

for (i, j) in generator(range(1, 4), range(1, 4)):
    print(i, j)
    if j == 2:
        break
Enter fullscreen mode Exit fullscreen mode

Follow the discussion on Twitter

Discussion (0)