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
Follow the discussion on Twitter
π‘π Let's have a look at nested loops in Python!
How can we break out π of both loops with code on the inner loop?
Let's have a look! π10:02 AM - 20 May 2022
Top comments (0)