DEV Community

Bas Steins
Bas Steins

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

Top comments (0)