clever exit of nested loops

John Ladasky john_ladasky at sbcglobal.net
Thu Sep 27 04:00:36 EDT 2018


On Wednesday, September 26, 2018 at 12:50:20 AM UTC-7, vito.d... at gmail.com wrote:

> I have "abused" the "else" clause of the loops to makes a break "broke" more loops

I did this once upon a time.  In recent years, when I start writing tricky nested loops, I frequently find myself reaching for itertools.product() to flatten the loops instead.

This code accomplishes the same task as yours.  I'll leave it to you to decide whether you prefer it.  There are things that I dislike about it, but the flow control part is clear.


from itertools import product

msgs = ("i: {}", "\tj: {}", "\t\tk: {}")
old = 3*[None]
for new in product(range(10), repeat=3):
    for n, (msg, changed) in enumerate(zip(msgs, [x!=y for x, y in zip(old, new)])):
        if changed:
            print(msg.format(new[n]))
    if condition(*new):    # your condition() took three separate arguments
        break
    old = new




More information about the Python-list mailing list