Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break the nested (double) loop in Python [duplicate]

I use the following method to break the double loop in Python.

for word1 in buf1:     find = False     for word2 in buf2:         ...         if res == res1:             print "BINGO " + word1 + ":" + word2             find = True     if find:         break 

Is there a better way to break the double loop?

like image 711
prosseek Avatar asked Apr 08 '10 02:04

prosseek


People also ask

How does break work in nested loops Python?

The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.

How do you break a nested loop?

Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.

Does a break in a nested loop break both loops?

You can break all loops with else and continue . The code with explanation is as follows. When the inner loop ends normally without break , continue in the else clause is executed. This continue is for the outer loop, and skips break in the outer loop and continues to the next cycle.


2 Answers

Probably not what you are hoping for, but usually you would want to have a break after setting find to True

for word1 in buf1:      find = False      for word2 in buf2:          ...          if res == res1:              print "BINGO " + word1 + ":" + word2              find = True              break             # <-- break here too     if find:          break  

Another way is to use a generator expression to squash the for into a single loop

for word1, word2 in ((w1, w2) for w1 in buf1 for w2 in buf2):     ...      if res == res1:          print "BINGO " + word1 + ":" + word2         break  

You may also consider using itertools.product

from itertools import product for word1, word2 in product(buf1, buf2):     ...      if res == res1:          print "BINGO " + word1 + ":" + word2         break  
like image 82
John La Rooy Avatar answered Sep 21 '22 07:09

John La Rooy


The recommended way in Python for breaking nested loops is... Exception

class Found(Exception): pass try:     for i in range(100):         for j in range(1000):             for k in range(10000):                if i + j + k == 777:                   raise Found except Found:     print i, j, k  
like image 31
Guard Avatar answered Sep 24 '22 07:09

Guard