Python: Continuing to next iteration in outer loop

Viewed 167091

I wanted to know if there are any built-in ways to continue to next iteration in outer loop in python. For example, consider the code:

for ii in range(200):
    for jj in range(200, 400):
        ...block0...
        if something:
            continue
    ...block1...

I want this continue statement to exit the jj loop and goto next item in the ii loop. I can implement this logic in some other way (by setting a flag variable), but is there an easy way to do this, or is this like asking for too much?

9 Answers

I think one of the easiest ways to achieve this is to replace "continue" with "break" statement,i.e.

for ii in range(200):
 for jj in range(200, 400):
    ...block0...
    if something:
        break
 ...block1...       

For example, here is the easy code to see how exactly it goes on:

for i in range(10):
    print("doing outer loop")
    print("i=",i)
    for p in range(10):
        print("doing inner loop")
        print("p=",p)
        if p==3:
            print("breaking from inner loop")
            break
    print("doing some code in outer loop")

The best approach I know to continue an outer loop is using a Boolean that is scoped under the outer loop and breaking the inner one. Although, depending on the use case you may not break the inner loop, continuing an outer loop inside its inner loop implicitly suggests that you want to immediately jump to the first line of the outer loop and avoid any further execution in the inner one. That is why I added a break statement.

for i in range(0, 6):
    should_continue = False

    for f in range(1, i * 2):
        print(f"f = {f}")
        if (not (f % 1337) or not (f % 7)):
            print(f"{f} can be divided, continue outer loop")
            should_continue = True
            # leaves inner loop
            break

    if(should_continue): continue
    # Outer loop's code goes here
    print(f'Reached outer loop\ni = {i}')

This approach avoids calling any functions and dealing with possible drawbacks. Calling a function is known to be a rather expensive operation, specially for Games. Now imagine a deeply nested for loop that will run millions of times, wrapping it inside a function won't result in a smooth experience.

Wrapping the loop inside an exception block is also a bad idea and will be way slower than functions. This is because Python needs a lot of overhead to trigger the exceptions mechanism and later restore the runtime state, exceptions are designed to be used exceptionally. Taking that in mind, even some CPU optimizations such as speculative execution should not be applied to exception blocks and probably aren't.

The only "problem" I found in this approach is that break will jump once outside of the inner loop, landing on continue, which, in turn, will jump one more time. This, as opposed to a goto statement in C or JavaScript, is a bit more clumsy, but doesn't have any visible impact in performance, because it would generate only one extra instruction that runs as fast as your CPU's clock or as the interpreter implementation.

I just did something like this. My solution for this was to replace the interior for loop with a list comprehension.

for ii in range(200):
    done = any([op(ii, jj) for jj in range(200, 400)])
    ...block0...
    if done:
        continue
    ...block1...

where op is some boolean operator acting on a combination of ii and jj. In my case, if any of the operations returned true, I was done.

This is really not that different from breaking the code out into a function, but I thought that using the "any" operator to do a logical OR on a list of booleans and doing the logic all in one line was interesting. It also avoids the function call.

Related