88

How can you continue the parent loop of say two nested loops in Python?

for a in b:
    for c in d:
        for e in f:
            if somecondition:
                <continue the for a in b loop?>

I know you can avoid this in the majority of cases but can it be done in Python?

5
  • 2
    any reason to not just use break ? Commented Feb 12, 2013 at 9:51
  • Use break to leave the inner loop - this'll immediately continue in the outer loop. Commented Feb 12, 2013 at 9:52
  • 2
    There's another similar question: stackoverflow.com/questions/189645/… Commented Feb 12, 2013 at 9:52
  • 3
    @JonClements I've fixed the example to actually need the continue. Commented Feb 12, 2013 at 9:55
  • when nesting loops, you should conside this technique: flatten nested loops. Commented Aug 8, 2023 at 12:37

8 Answers 8

84
  1. Break from the inner loop (if there's nothing else after it)
  2. Put the outer loop's body in a function and return from the function
  3. Raise an exception and catch it at the outer level
  4. Set a flag, break from the inner loop and test it at an outer level.
  5. Refactor the code so you no longer have to do this.

I would go with 5 every time.

Sign up to request clarification or add additional context in comments.

2 Comments

one of the cases where PHP beats Python, since it does have level options for break and continue :)
I would consider #2 to be the standard way to implement #5, unless there is a completely different approach to the problem in context.
31

Here's a bunch of hacky ways to do it:

  1. Create a local function

    for a in b:
        def doWork():
            for c in d:
                for e in f:
                    if somecondition:
                        return # <continue the for a in b loop?>
        doWork()
    

    A better option would be to move doWork somewhere else and pass its state as arguments.

  2. Use an exception

    class StopLookingForThings(Exception): pass
    
    for a in b:
        try:
            for c in d:
                for e in f:
                    if somecondition:
                        raise StopLookingForThings()
        except StopLookingForThings:
            pass
    

Comments

21

You use break to break out of the inner loop and continue with the parent

for a in b:
    for c in d:
        if somecondition:
            break # go back to parent loop

Comments

13
from itertools import product
for a in b:
    for c, e in product(d, f):
        if somecondition:
            break

Comments

4

use a boolean flag

problem = False
for a in b:
  for c in d:
    if problem:
      continue
    for e in f:
        if somecondition:
            problem = True

Comments

1

Looking at All the answers here its all different from how i do it\n Mission:continue to while loop if the if condition is true in nested loop

chars = 'loop|ing'
x,i=10,0
while x>i:
    jump = False
    for a in chars:
      if(a = '|'): jump = True
    if(jump==True): continue

Comments

0
lista = ["hello1", "hello2" , "world"]

for index,word in enumerate(lista):
    found = False
    for i in range(1,3):
        if word == "hello"+str(i):
            found = True
            break
        print(index)
    if found == True:
        continue
    if word == "world":
        continue
    print(index)


    

Now what's printed :

>> 1
>> 2
>> 2

This means that the word no.1 ( index = 0 ) appeard first (there's no way for something to be printed before the continue statement). The word no.2 ( index = 1 ) appeared second ( the word "hello1" managed to be printed but not the rest ) and the word no.3 appeard third what mean's that the words "hello1" and "hello2" managed to be printed before the for loop reached this said third word.

To sum up it's just using the found = False / True boolean and the break statement.

Hope it helps!

Comments

0
#infinite wait till all items obtained
while True:
    time.sleep(0.5)
    for item in entries:
        if self.results.get(item,None) is None:
            print(f"waiting for {item} to be obtained")
            break #continue outer loop
    else:
        break
    #continue

I wish there could be a labeled loop ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.