Good day! There was a hitch with cycles in python. The essence of the problem is that when a certain value is found in the list "c", the list "a" goes to the next iteration, and the lists "b" and "c" are reset. I can not understand how to do this with a loop with a double attachment.

a = [1, 2, 3, 4, 5] b = [10, 20, 30, 40, 50] c = [100, 200, 300, 400, 500] for i in a: for j in b: for q in c: if q == 400: pass print(i, j, q) 

If a loop with one attachment - everything is very simple. The break instruction helps, the "b" cycle ends and a transition to the next iteration of the "a" cycle occurs:

 a = [1, 2, 3, 4, 5] b = [10, 20, 30, 40, 50] for i in a: for j in b: if j == 40: break print(i, j) 

and how to be in the first case?

2 answers 2

You can wrap two internal loops into a function, and when the desired value is reached, terminate it with return.

 a = [1, 2, 3, 4, 5] b = [10, 20, 30, 40, 50] c = [100, 200, 300, 400, 500] def inner(i): for j in b: for q in c: if q == 400: return None print(i, j, q) for i in a: inner(i) 
  • one
    You can simply use: return instead of return None . - jfs

Instead of creating a nested function, sometimes you can simply duplicate a condition or set the flag or use the for / else syntax:

 for i in a: for j in b: for q in c: if q == 400: break # inner loop print(i, j, q) else: # no break continue # middle loop break # middle loop 

The option with a nested function is easier to read and compact.