[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

clever exit of nested loops

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:
    if condition(*new):    # your condition() took three separate arguments
    old = new