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

🌐
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 - Python provides a built-in function called os.walk() that allows you to iterate over all files and folders within a root directory recursively, meaning it will go into subdirectories as well. Let’s see an example. You need to recursively scan all .txt files in a directory, search each line for a keyword, and immediately stop and report the file name when the keyword is found.
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
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
How can I break out of a while loop immediately and at any point during the while loop.
Literally, this is what the break statement does. More on reddit.com
🌐 r/learnpython
32
0
June 23, 2023
🌐
LearnPython.com
learnpython.com › blog › end-loop-python
How to End Loops in Python | LearnPython.com
December 16, 2021 - In the example above, we progress through the sequence starting at -2, taking steps of 3, and then we stop at 10. This is before the defined stop value of 11, but an additional step of 3 takes us beyond the stop value.
🌐
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.
🌐
Replit
replit.com › home › discover › how to stop a loop in python
How to stop a loop in Python | Replit
February 13, 2026 - This block of code runs only when ... clean way to check if a loop completed its full run. In this example, the loop stops when i is 5 because of the break....
🌐
Real Python
realpython.com › python-break
How to Exit Loops Early With the Python break Keyword – Real Python
April 16, 2025 - It’s a Python keyword that, when used in a loop, immediately exits the loop and transfers control to the code that would normally run after the loop’s standard conclusion. You can see the basics of the break statement in a simple example.
Find elsewhere
🌐
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 ...
🌐
Real Python
realpython.com › python-while-loop
Python while Loops: Repeating Tasks Conditionally – Real Python
March 3, 2025 - In this tutorial, you'll learn about indefinite iteration using the Python while loop. You'll be able to construct basic and complex while loops, interrupt loop execution with break and continue, use the else clause with a while loop, and deal with infinite loops.
🌐
Delft Stack
delftstack.com › home › howto › python › stop a for loop in python
How to Stop a for Loop in Python | Delft Stack
February 9, 2025 - Counter value= 0 counter value<3. Continue the for loop. Counter value= 1 counter value<3. Continue the for loop. Counter value= 2 counter value=3. Stop the for loop · Here, as long as the for loop criteria is met, the following print statement is printed. For example -
🌐
Problem Solving with Python
problemsolvingwithpython.com › 09-Loops › 09.03-Break-and-Continue
Break and Continue - Problem Solving with Python
An example using break in a for loop is below. ... When the loop hits i=3, break is encountered and the program exits the loop. An example using break in a while loop is below. ... In Python, the keyword continue causes the program to stop running code in a loop and start back at the top of ...
🌐
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 ...
🌐
LearnDataSci
learndatasci.com › solutions › python-break
Python break statement: break for loops and while loops – LearnDataSci
The flowchart below shows the process that Python is following in our example: ... break will terminate the nearest encompassing loop, but this can get a little confusing when working with nested loops. It's important to remember that break only ends the inner-most loop when used in a script with multiple active loops. ... strings = ['This ', 'is ', 'a ', 'list '] # iterate through each string in the list for string in strings: # iterate through each character in the string for char in string: print(char) if char == 'i': # if the character is equal to 'i', terminate the nested for loop print('break\n') break
🌐
Manifoldapp
cuny.manifoldapp.org › read › how-to-code-in-python-3 › section › 8adf4bec-a6ca-4a11-8c8d-4cf4052d5ac4
How To Use Break, Continue, and Pass Statements when Working with Loops | How To Code in Python 3 | Manifold @CUNY
In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You’ll put the break statement within the block of code under your loop statement, usually after a conditional if statement. Let’s look at an example that uses ...
🌐
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 - Then we'll look at some of the methods we can use to break nested loops in Python. You define the break statement in the loop you want it to terminate. In this section, we'll see how to use the break statement in for and while loops.
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python for loop continue and break
Python For Loop Continue And Break - Spark By {Examples}
April 17, 2024 - The example is given below. If the break statement is inside a nested loop, the break statement will end the innermost loop and the outer loop continue executing. ... # Using break statement inside the nested loop ourses1=["java","python"] ...
🌐
Programiz
programiz.com › python-programming › break-continue
Python break and continue (With Examples)
We can use the break statement with the for loop to terminate the loop when a certain condition is met. For example, ... Note: We can also terminate the while loop using a break statement.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-break-statement
Python break statement - GeeksforGeeks
In the above example, when n becomes 5, the condition n == val becomes True. The break statement exits the inner loop immediately. Since found is set to True, the outer loop also exits.
Published   2 weeks ago
🌐
EyeHunts
tutorial.eyehunts.com › home › python stop for loop
Python stop for loop
July 27, 2023 - Once we find an even number, we’ll ... result. numbers = [23, 14, 17, 6, 31, 12, 9, 8] for num in numbers: if num % 2 == 0: # Check if the number is even print(f"Found the first even number: {num}") break else: print("No even number found in the list.") ... numbers ...
🌐
Python Morsels
pythonmorsels.com › breaking-out-of-a-loop
Breaking out of a loop - Python Morsels
June 26, 2025 - At this point, it might actually be easier to put this code into a function, and use return to break out of that inner loop as well as the outer loop at the same time. 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 print("Adding", n) total += n print("Total:", total)