Python Forum
best way out of nested loops? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: best way out of nested loops? (/thread-27124.html)



best way out of nested loops? - Skaperen - May-27-2020

the best and most Pythonic way (in your opinion) to get all the way out of a few nested loops is?


RE: best way out of nested loops? - Knight18 - May-27-2020

Break statement I guess? Or if you're looking for something more drastic, sys.exit?


RE: best way out of nested loops? - buran - May-27-2020

maybe look for way to refactor code without nested loops (can you use itertools.product and break?)?
maybe separate loops in function and return?


RE: best way out of nested loops? - buran - May-27-2020

(May-27-2020, 07:21 AM)Knight18 Wrote: Break statement I guess?
just break will break out of the one specific loop, but the question is about nested loops and break out all the way


RE: best way out of nested loops? - jefsummers - May-27-2020

My kludge would be to set a flag in that innermost loop, and then test for the flag when coming out (and break again). This works:
for loop1 in range(10):
    for loop2 in range(10):
        for loop3 in range(10):
            for loop4 in range(10):
                x = input('break')
                flag = True
                break
            if flag:
                break
            #do other stuff
        if flag:
            break
        #do other stuff
    if flag:
        break
    #do more other stuff



RE: best way out of nested loops? - DeaD_EyE - May-27-2020

@jefsummers your solution is a candidate for refactoring.

def loop():
    for i in range(10):
        for j in range(10):
            if i*j > 10:
                return i, j
Just put everything in a function, return if the condition is fulfilled.
If tasks afterwards are necessary, you could work with the return value of the loop function.


RE: best way out of nested loops? - deanhystad - May-28-2020

I would try to flatten the logic if I could. Failing that I would try to "return" out. Failing that I would raise an exception.


RE: best way out of nested loops? - Skaperen - May-30-2020

i like the function idea. but that has the context problem where you might need to pass lots of data. that is where refactoring is needed. i think raising an exception is a kludge. exceptions have a purpose and this is not it. still, it can be a quick way to get at this kind of issue when the cost (such as time) of refactoring is too high.