Use break and continue to do this. Breaking nested loops can be done in Python using the following:

for a in range(...):
   for b in range(..):
      if some condition:
         # break the inner loop
         break
   else:
      # will be called if the previous loop did not end with a `break` 
      continue
   # but here we end up right after breaking the inner loop, so we can
   # simply break the outer loop as well
   break

Another way is to wrap everything in a function and use return to escape from the loop.

Answer from Alexander Gessler on Stack Overflow
Top answer
1 of 7
129

Use break and continue to do this. Breaking nested loops can be done in Python using the following:

for a in range(...):
   for b in range(..):
      if some condition:
         # break the inner loop
         break
   else:
      # will be called if the previous loop did not end with a `break` 
      continue
   # but here we end up right after breaking the inner loop, so we can
   # simply break the outer loop as well
   break

Another way is to wrap everything in a function and use return to escape from the loop.

2 of 7
72

There are several ways to do it:

The simple Way: a sentinel variable

n = L[0][0]
m = len(A)
found = False
for i in range(m):
   if found:
      break
   for j in range(m):
     if L[i][j] != n: 
       found = True
       break

Pros: easy to understand Cons: additional conditional statement for every loop

The hacky Way: raising an exception

n = L[0][0]
m = len(A)

try:
  for x in range(3):
    for z in range(3):
     if L[i][j] != n: 
       raise StopIteration
except StopIteration:
   pass

Pros: very straightforward Cons: you use Exception outside of their semantic

The clean Way: make a function

def is_different_value(l, elem, size):
  for x in range(size):
    for z in range(size):
     if l[i][j] != elem: 
       return True
  return False
   
if is_different_value(L, L[0][0], len(A)):
  print "Doh"

pros: much cleaner and still efficient cons: yet feels like C

The pythonic way: use iteration as it should be

def is_different_value(iterable):
  first = iterable[0][0]
  for l in iterable:
    for elem in l:
       if elem != first: 
          return True
  return False
   
if is_different_value(L):
  print "Doh"

pros: still clean and efficient cons: you reinvdent the wheel

The guru way: use any():

def is_different_value(iterable):
  first = iterable[0][0]
  return any(cell != first for col in iterable for cell in col)

if is_different_value(L):
  print "Doh"

pros: you'll feel empowered with dark powers cons: people that will read you code may start to dislike you

🌐
W3Schools
w3schools.com › python › python_for_loops.asp
Python For Loops
Note: The else block will NOT be executed if the loop is stopped by a break statement. Break the loop when x is 3, and see what happens with the else block: for x in range(6): if x == 3: break print(x) else: print("Finally finished!") Try it ...
Discussions

How do I end a For or While loop without using break?
A for loop ends when it exhausts its iterable, and a while loop terminates when its condition is no longer met. If you were going to write while True: if some_variable == "some value": break #do stuff then instead you could write: while some_variable != "some value": #do stuff More on reddit.com
🌐 r/learnpython
4
4
March 19, 2022
Breaking/continuing out of multiple loops - Ideas - Discussions on Python.org
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 ... More on discuss.python.org
🌐 discuss.python.org
4
August 21, 2022
How to Break out of a loop without waiting for the current iteration to complete?
Use multiprocessing.Process(), it works like Thread but it has a terminate() method. from multiprocessing import Process import keyboard def main(): while True: func() if __name__ == '__main__': process = Process(target=main) process.start() while process.is_alive(): if keyboard.is_pressed('q'): process.terminate() break More on reddit.com
🌐 r/learnpython
4
1
March 4, 2023
How to stop an infinite while loop?
while True: print("test") break I assume this is what you're looking for. The break keyword will end any loop (even for loops) and skip to the first command after the loop (as if the loop had ended normally) More on reddit.com
🌐 r/learnpython
4
0
November 25, 2022
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-break-continue-and-pass-statements-when-working-with-loops-in-python-3
How to Break Out of Multiple Loops in Python | DigitalOcean
August 7, 2025 - For instance, you might encounter ... placeholder for future code. Python provides three powerful statements to handle these cases: break, continue, and pass. The break statement allows you to exit a loop entirely when a specific condition is met, effectively stopping the loop ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-break-statement
Python break statement - GeeksforGeeks
The break statement can be used within a for loop to exit the loop before it has iterated over all items, based on a specified condition. ... A while loop in Python repeatedly executes a block of code as long as a specified condition is True.
Published   3 weeks ago
🌐
Pierian Training
pieriantraining.com › home › python tutorial: how to stop an infinite loop in python
Python Tutorial: How to stop an infinite loop in Python - Pierian Training
April 12, 2023 - To avoid infinite loops in your Python programs, it’s important to carefully check your loop conditions and make sure they are correct. Additionally, you can use tools like break statements or timeouts to stop a loop that has been running for too long.
🌐
Enki
enki.com › post › how-to-exit-a-loop-in-python
Enki | Blog - How to Exit a Loop in Python
The break statement helps us terminate or exit a loop before its natural end. It stops the loop immediately, bypassing any remaining iterations. This loop would normally run forever because while True sets an infinite loop. Here, break halts it once i reaches 5.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › break-continue-and-pass-in-python
Loop Control Statements - Python
July 12, 2025 - # Using For Loop for i in range(5): if i == 3: break # Exit the loop when i is 3 print(i) # Using While Loop i = 0 while i < 5: if i == 3: break # Exit the loop when i is 3 print(i) i += 1 ... Python Continue statement is a loop control statement that forces to execute the next iteration of the loop while skipping the rest of the code inside the loop for the current iteration only, i.e.
🌐
Python Morsels
pythonmorsels.com › breaking-out-of-a-loop
Breaking out of a loop - Python Morsels
June 26, 2025 - In addition to the break statement, Python also has a continue statement: with open("numbers.txt") as number_file: total = 0 for line in number_file: for number in line.split(): n = float(number) if n < 0: print("Skipping negative", n) continue ...
🌐
Finxter
blog.finxter.com › home › learn python blog › how to stop a for loop in python
How to Stop a For Loop in Python - Be on the Right Side of Change
September 28, 2022 - The most natural way to end a Python for loop is to deplete the iterator defined in the loop expression for <var> in <iterator>. If the iterator’s next() method doesn’t return a value anymore, the program proceeds with the next statement ...
🌐
freeCodeCamp
freecodecamp.org › news › python-break-statement-tutorial
Python Break Statement – How to Break Out of a For Loop in Python
April 16, 2024 - usernames = ["Jade", "John", "Jane", ... value of i is "John": if i == "John". In the body of the if statement, we used the break statement. So the loop will stop when it finds an element in the list with the value of ...
🌐
freeCodeCamp
freecodecamp.org › news › break-in-python-nested-for-loop-break-if-condition-met-example
Break in Python – Nested For Loop Break if Condition Met Example
May 17, 2022 - The code above prints a range of ... terminated instead of printing all the way to 9. In this section, we'll see how to use the break statement in nested loops....
🌐
freeCodeCamp
freecodecamp.org › news › python-break-and-python-continue-how-to-skip-to-the-next-function
Python Break and Python Continue – How to Skip to the Next Function
March 14, 2022 - In this first example we have a ... ... If we wanted to stop our loop at the letter "o", then we can use an if statement followed by a break statement....
🌐
Python documentation
docs.python.org › 3 › tutorial › controlflow.html
4. More Control Flow Tools — Python 3.14.3 documentation
In either kind of loop, the else clause is not executed if the loop was terminated by a break. Of course, other ways of ending the loop early, such as a return or a raised exception, will also skip execution of the else clause. This is exemplified in the following for loop, which searches for prime numbers:
🌐
IONOS
ionos.com › digital guide › websites › web development › python break continue
How to use Python break and continue - IONOS
July 13, 2023 - Like the above example, a loop can also be created with Python continue. However, the loop should count, start at 0 and stop at 9 this time. The number is also smaller than 10 in this condition, but if the counting mechanism reaches 5, the loop should be in­ter­rupt­ed, but not ter­mi­nat­ed. This is how the code is written: for num in range(10): if num == 5: continue print(f"The current number is {num}") print("Continuation after loop")
🌐
LearnPython.com
learnpython.com › blog › end-loop-python
How to End Loops in Python | LearnPython.com
December 16, 2021 - If you want to see some concrete examples of how to apply these two functions for efficient looping, check out this article. The break statement is the first of three loop control statements in Python.
🌐
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 ...
🌐
Tutorialspoint
tutorialspoint.com › python › python_break_statement.htm
Python - break Statement
In this example, we will see the working of break statement in for loop. for letter in 'Python': if letter == 'h': break print ("Current Letter :", letter) print ("Good bye!")
🌐
W3Schools
w3schools.com › python › ref_keyword_break.asp
Python break Keyword
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... The break keyword is used to break out ...
🌐
Real Python
realpython.com › python-break
How to Exit Loops Early With the Python break Keyword – Real Python
February 25, 2025 - Here’s how your adjusted code might look in this case, using a break statement: ... >>> scores = [90, 30, 50, 70, 85, 35] >>> num_failed_scores = 0 >>> pass_score = 60 >>> needs_tutoring = "No" >>> for score in scores: ...