## DEV Community is a community of 867,901 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

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)
``````

## `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
``````

## `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
``````

## 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
``````