Search code examples
pythonnested-loops

Break the nested (double) loop in Python


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?


Solution

  • 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