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.

Answer from Duncan on Stack Overflow
🌐
Python.org
discuss.python.org › ideas
Breaking/continuing out of multiple loops - Ideas - Discussions on Python.org
August 21, 2022 - Hi! SUGGESTION An easy way to break/continue within nested loops. MY REAL LIFE EXAMPLE I am looping through a list of basketball players, each of which has multiple tables, each of which can have up to three different versions. I manipulate data in the deepest loop and, if some key data is ...
Discussions

Python: Continuing to next iteration in outer loop - Stack Overflow
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 ... More on stackoverflow.com
🌐 stackoverflow.com
December 4, 2016
Using Continue Statement in nested for loop in Python - Stack Overflow
Hi I have a function that read in data from two files. What I want to be happening is that the outer loop starts to read in the the first file and if lum from the first file is greater than the de... More on stackoverflow.com
🌐 stackoverflow.com
python - How to continue a loop while being in a nested loop? - Stack Overflow
I'm using a loop and a nested loop, and i need the outer loop to stop whenever the second reaches a certain value. for first in range(0,10): for second in range(0,10): print(first + second) ... More on stackoverflow.com
🌐 stackoverflow.com
Nested for loops - how to leave inner loop, to go to outer loop's next iteration, but also continue inner loop's iteration?
You need one loop for that, obviously. First idea: i, j = 7, 11 while j < 1000: print (i, '\t', j) i += 80 j += 81 You can try calculating i and j from some basic index each iteration: for x in range(13): i = 7+80*x j = 11+81*x print (i, '\t', j) Of course, Python allows for and range for that, too, using zip: for i, j in zip(range (7, 1000, 80), range(11, 1000, 81)): print (i, '\t', j) When you encounter some complex loop question, try disassembling it to a while loop until it works, and then try to get it back into for. More on reddit.com
🌐 r/learnpython
12
3
August 12, 2025
🌐
Reddit
reddit.com › r/python › (over?)use of continue in for loops in python
r/Python on Reddit: (Over?)use of continue in for loops in python
November 17, 2021 -

Hi! I don't have much experience (around 3 years of not full-time programming) and was wondering what do you think about the use of 'continue' statement in for loops

In the project I'm working on there is a need to make a lot of validations.What usually happens we program using a lot of 'if' and 'elif' and 'else'So the indentations make the code wider than a Dubai highway...

What I thought about is calling methods for error controlling (logs the issue and returns False)and using continue for the next item in the loop

What do you think?

(Some colleagues tried to create different Classes for each of the validation but IMO it gets the code too twisted and practically impossible to debug - may work in a bigger project)

🌐
PYnative
pynative.com › home › python › nested loops in python
Python Nested Loops [With Examples] – PYnative
September 2, 2021 - ... for i in range(4): for j in ... see in the output, no rows contain the same number. The continue statement skip the current iteration and move to the next iteration....
🌐
AskPython
askpython.com › home › python continue statement
Python continue Statement - AskPython
July 7, 2022 - We can’t use continue statement ... while loops. If the continue statement is present in a nested loop, it skips the execution of the inner loop only....
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-continue-statement
Python Continue Statement - GeeksforGeeks
The continue statement in Python is a loop control statement that skips the rest of the code inside the loop for the current iteration and moves to the next iteration immediately.
Published   3 days ago
🌐
Note.nkmk.me
note.nkmk.me › home › python
Break Out of Nested Loops in Python | note.nkmk.me
August 18, 2023 - Note that this will not work if run as a Python script. ... Please note that the results may vary depending on the number of elements and the depth of nested for loops. ... import itertools n = 100 l1 = range(n) l2 = range(n) l3 = range(n) x = n - 1 %%timeit for i in l1: for j in l2: for k in l3: if i == x and j == x and k == x: break else: continue break else: continue break # 43 ms ± 1.33 ms per loop (mean ± std.
Find elsewhere
🌐
Real Python
realpython.com › python-continue
Skip Ahead in Loops With Python's continue Keyword – Real Python
March 27, 2025 - The official Python documentation for continue describes how this works: continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop [emphasis added]. It continues with ...
Top answer
1 of 9
246
Copyfor ii in range(200):
    for jj in range(200, 400):
        ...block0...
        if something:
            break
    else:
        ...block1...

Break will break the inner loop, and block1 won't be executed (it will run only if the inner loop is exited normally).

2 of 9
130
Copyfor i in ...:
    for j in ...:
        for k in ...:
            if something:
                # continue loop i

In a general case, when you have multiple levels of looping and break does not work for you (because you want to continue one of the upper loops, not the one right above the current one), you can do one of the following

Refactor the loops you want to escape from into a function

Copydef inner():
    for j in ...:
        for k in ...:
            if something:
                return


for i in ...:
    inner()

The disadvantage is that you may need to pass to that new function some variables, which were previously in scope. You can either just pass them as parameters, make them instance variables on an object (create a new object just for this function, if it makes sense), or global variables, singletons, whatever (ehm, ehm).

Or you can define inner as a nested function and let it just capture what it needs (may be slower?)

Copyfor i in ...:
    def inner():
        for j in ...:
            for k in ...:
                if something:
                    return
    inner()

Use exceptions

Philosophically, this is what exceptions are for, breaking the program flow through the structured programming building blocks (if, for, while) when necessary.

The advantage is that you don't have to break the single piece of code into multiple parts. This is good if it is some kind of computation that you are designing while writing it in Python. Introducing abstractions at this early point may slow you down.

Bad thing with this approach is that interpreter/compiler authors usually assume that exceptions are exceptional and optimize for them accordingly.

Copyclass ContinueI(Exception):
    pass


continue_i = ContinueI()

for i in ...:
    try:
        for j in ...:
            for k in ...:
                if something:
                    raise continue_i
    except ContinueI:
        continue

Create a special exception class for this, so that you don't risk accidentally silencing some other exception.

Something else entirely

I am sure there are still other solutions.

🌐
Python
docs.python.org › 2.0 › ref › continue.html
6.10 The continue statement
continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition or try statement within that loop.6.1It continues with the next cycle of the nearest enclosing loop.
🌐
Real Python
realpython.com › nested-loops-python
Nested Loops in Python – Real Python
May 21, 2025 - If a nested for loop were a BLT sandwich, using break would be like eating the top layers and discarding the rest. Using continue, on the other hand, would be like eating the top layers, skipping the lettuce, then finishing the bottom layers.
🌐
LWN.net
lwn.net › Articles › 906512
Python multi-level break and continue [LWN.net]
August 31, 2022 - Suter agreed with that to a certain extent, noting the first search result for "python multiple for loop break" is a Stack Overflow answer that is overly clever. Suter adapted it to the original example as follows: for sport in all_sports: # "for sport" loop for player in all_players: for player_tables in all_tables: # "for player_tables" loop for version in player_tables: # things have gone wrong, go to next iteration of all_sports loop break else: continue break else: continue break That uses the else clause for loops, which will execute if no break is used in the loop, thus the loop runs to completion.
🌐
H2K Infosys
h2kinfosys.com › blog › python break, continue and pass statements in loops
Python Break, Continue, and Pass Statements: The Ultimate Guide
January 5, 2026 - Using the continue statement in nested loops. Using the pass statement. Without further ado, let’s jump into it. The Python Break statement is used to terminate a loop abruptly, based on another condition. When a Python Break statement is used in a nested loop, the inner loop does not run anytime the specific condition is met.
🌐
Learn Python
learnpython.dev › 02-introduction-to-python › 110-control-statements-looping › 40-break-continue
break, continue, and return :: Learn Python by Nina Zakharenko
break and continue allow you to control the flow of your loops. They’re a concept that beginners to Python tend to misunderstand, so pay careful attention. Using break The break statement will completely break out of the current loop, meaning it won’t run any more of the statements contained inside of it.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-nested-loops
Python Nested Loops - GeeksforGeeks
The continue statement skips the rest of the code for the current iteration and moves to the next iteration of the loop. ... 2 * 1 = 2 2 * 3 = 6 2 * 4 = 8 2 * 5 = 10 2 * 6 = 12 2 * 7 = 14 2 * 8 = 16 2 * 9 = 18 2 * 10 = 20 3 * 1 = 3 3 * 2 = 6 ...
Published   4 days ago
Top answer
1 of 1
2

You seem to be expecting nlines to behave like a list. However, it is instead an iterator, and as Ignacio pointed out above, it will be consumed once. In other words, the inner loop doesn't get "reset" to the first line/index on subsequent outer loop executions.

Consider the following analog (I think) to what you're doing. Here are two data files:

Data1:

file 1: one
file 1: two
file 1: three
file 1: four
file 1: five

Data2:

file 2: one
file 2: two
file 2: three
file 2: four
file 2: five
file 2: six

Running this:

from itertools import islice

f1 = open ("Data1")
f2 = open ("Data2")

iterator1 = islice (f1, 3)
iterator2 = islice (f2, 3)

for line1 in iterator1:
    print line1

    for line2 in iterator2:
       print line2

results in:

file 1: one
file 2: one
file 2: two
file 2: three
file 1: two
file 1: three

whereas one might erroneously expect that 3 lines of the contents of data2 would be printed for each of the first 3 lines of data1.

So, the first execution of the inner loop fully consumes iterator2. In your own code there is no inner loop break when id == idc - in other words, you consume interator nlines completely the first time that inner loop executes.

See also, Python: itertools.islice not working in a loop for another example.

One solution may be to break in the inner loop when id == idc, but this will assume (I think) an ordering of indices in your second file. You could consider actually using a list for the inner loop, although that seems memory-intensive given the size of your actual (non-test) data. You could obviously reread that second file, although performance will take a hit.

🌐
GitHub
github.com › python › cpython › issues › 101935
Add new combination of keywords: "break and continue" inside a nested loop breaks the inner and continues in the outer · Issue #101935 · python/cpython
for index,row in tqdm(cellmesh_dataset.iterrows()): [...] for gene in list_of_genes: tokenized_gene = tokenizer(gene) match_indexes = search_list_in_list(tokenized_context, tokenized_gene) if match_indexes == -1: break and continue # <--- this line now breaks the inner loop and continues in the outer for index in match_indexes: for i in range(len(tokenized_gene)): outputs[index+i] = 1.0 [...]
Author   ghost
🌐
iO Flood
ioflood.com › blog › python-continue
Python Continue | Flow Control Keyword Guide
June 12, 2024 - In this example, we have two nested loops iterating over the range from 1 to 3. The ‘continue’ statement is used to skip the iteration when the values of i and j are equal. This is why you don’t see any output where i equals j. The ...
🌐
Stack Overflow
stackoverflow.com › questions › 74459602 › how-to-continue-a-loop-while-being-in-a-nested-loop
python - How to continue a loop while being in a nested loop? - Stack Overflow
break breaks out of the inner loop only, which jumps to the after the inner loop. Assuming that there’s no code immediately after the inner loop, then the current iteration of the outer loop will end and the next one will start. So I think using break instead of continue should do exactly what you want.
🌐
Programiz
programiz.com › python-programming › break-continue
Python break and continue (With Examples)
We can also terminate the while loop using the break statement. For example, i = 0 while i < 5: if i == 3: break print(i) i += 1 ... The continue statement skips the current iteration of the loop and the control flow of the program goes to the next iteration.