How to continue in nested loops in Python

Python

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

  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.

Solution 2 - Python

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
    

Solution 3 - Python

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

Solution 4 - Python

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

Solution 5 - Python

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

Solution 6 - Python

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

Solution 7 - Python

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJamesView Question on Stackoverflow
Solution 1 - PythonDuncanView Answer on Stackoverflow
Solution 2 - PythonEricView Answer on Stackoverflow
Solution 3 - PythonTony The LionView Answer on Stackoverflow
Solution 4 - PythonJohn La RooyView Answer on Stackoverflow
Solution 5 - PythonSamouraiView Answer on Stackoverflow
Solution 6 - PythonChesIngosanView Answer on Stackoverflow
Solution 7 - PythonIgnacio Javier Kairuz EguiaView Answer on Stackoverflow