-1

I have 3 loops. I would like to when the innermost loop meets a specific condition, exit from 2 inner loops and continue the outer loop.

for i in range(0,3):
    for j in range(0,4):
        for k in range(0,5):
            if k == 3:
                break
            print(i,j,k)

My output is :
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
1 0 0
1 0 1
1 0 2
1 1 0
1 1 1
1 1 2
but I would like to get to:
0 0 0
0 0 1
0 0 2
1 0 0
1 0 1
1 0 2
Danial
  • 7
  • 4

1 Answers1

-1

I would add a boolean in order to exit the second one:

for i in range(0,2):  # change the end of range in order to have the wanted print.
    exit_second_loop = False
    for j in range(0,4):
        if exit_second_loop:
            break
        for k in range(0,5):
            if k == 3:
                exit_second_loop = True
                break
            print(i,j,k)

This prints:

0 0 0
0 0 1
0 0 2
1 0 0
1 0 1
1 0 2

Edit:

A more elegant solution:

j = 0
for i in range(0, 2):
    for k in range(0, 3):
        print(i, j, k)

A another solution using product:

from itertools import product
j = 0
[print(i, j, k) for i, k in product(range(0, 2), range(0, 3))]
ndclt
  • 2,590
  • 2
  • 12
  • 26