DEV Community

Bas Steins
Bas Steins

Posted on

5 3

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

Neon image

Set up a Neon project in seconds and connect from a Python application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started β†’

Top comments (0)

Image of Quadratic

Python + AI + Spreadsheet

Chat with your data and get insights in seconds with the all-in-one spreadsheet that connects to your data, supports code natively, and has built-in AI.

Try Quadratic free

πŸ‘‹ Kindness is contagious

Dive into this insightful write-up, celebrated within the collaborative DEV Community. Developers at any stage are invited to contribute and elevate our shared skills.

A simple "thank you" can boost someone’s spiritsβ€”leave your kudos in the comments!

On DEV, exchanging ideas fuels progress and deepens our connections. If this post helped you, a brief note of thanks goes a long way.

Okay