+ 2

How to break two nested loops at the same time in python?

For Example:- for i in range(4): for j in range(1,5): if i + j == 5: break I want to stop this function once i+j is 5. But the break statement only stops one loop. How can i break both loops......???

5th Jul 2020, 10:37 AM
Anaswar K B
5 ответов
+ 9
If you put the nested loops together in a comprehension and a regular for loop, this should work (the comprehension creates number pairs and returned it as a pair of tuple). I found something similar with this principle in stack oveflow, and adapted it to this: for pair in [(i, j) for i in range(4) for j in range(1,5)]: print(pair) # for test only if sum(pair) == 5: break An other solution could be to put the loops in a function, that can break both loops by using return.
5th Jul 2020, 12:32 PM
Lothar
Lothar - avatar
+ 7
To add a dirty solution, put loop into try-except block. try: for i in range(4): for j in range(1,5): assert i + j != 5 except AssertionError: pass
5th Jul 2020, 11:12 AM
Russ
Russ - avatar
+ 4
You can also add the same statement to the other loop also. Although, they are nested but they'll always be 2 loops not 1
5th Jul 2020, 10:44 AM
Arctic Fox
Arctic Fox - avatar