A common construct is to run a loop until something is found and then to break out of the loop. The problem is that if I break out of the loop or the loop ends I need to determine which case happened. One method is to create a flag or store variable that will let me do a second test to see how the loop was exited.

For example assume that I need to search through a list and process each item until a flag item is found and then stop processing. If the flag item is missing then an exception needs to be raised.

Using the Python for...else construct you have

for i in mylist:
    if i == theflag:
        break
    process(i)
else:
    raise ValueError("List argument missing terminal flag.")

Compare this to a method that does not use this syntactic sugar:

flagfound = False
for i in mylist:
    if i == theflag:
        flagfound = True
        break
    process(i)

if not flagfound:
    raise ValueError("List argument missing terminal flag.")

In the first case the raise is bound tightly to the for loop it works with. In the second the binding is not as strong and errors may be introduced during maintenance.

Answer from Lance Helsten on Stack Overflow
🌐
W3Schools
w3schools.com › python › python_if_else.asp
Python Else Statement
Python Examples Python Compiler ... Interview Q&A Python Bootcamp Python Training ... The else keyword catches anything which isn't caught by the preceding conditions....
🌐
W3Schools
w3schools.com › python › gloss_python_for_else.asp
Python For Else
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

Why do for loops have an else block?
https://book.pythontips.com/en/latest/for_-_else.html More on reddit.com
🌐 r/Python
129
307
August 25, 2022
I've rewritten my core engine 20+ times over 2 years, And I know it's only the beginning.
20+ times? Im sorry my friend, but there is something wrong there. You could have maybe one big rewrite, but over 20??? What kind of system is this that its so complicated? And yeah, you can use AI. You could maybe get Claude Opus to plan the whole thing and then start writing based on those specs. But still, you are approaching this code in a very wrong way if you need 20+ rewrite More on reddit.com
🌐 r/Python
41
0
April 22, 2026
ALEX EXPLAINS: PYTHON 101 — PROFESSIONAL PROGRAMMING ETIQUETTE
Hey Alex! A lot of great information and insight here as well as encouragement! I am a beginner and I just started in March and I feel lost and overwhelmed at times and reading your post here really made me feel better about how I have been doing. Thank you so much for sharing!! More on reddit.com
🌐 r/maestro
23
20
April 22, 2026
Rhai vs Lua (Or else) for config/scripting Language
Lua is definitely more popular, if you want a good rust example you can look at wezterm More on reddit.com
🌐 r/rust
21
19
April 6, 2026
Top answer
1 of 16
948

A common construct is to run a loop until something is found and then to break out of the loop. The problem is that if I break out of the loop or the loop ends I need to determine which case happened. One method is to create a flag or store variable that will let me do a second test to see how the loop was exited.

For example assume that I need to search through a list and process each item until a flag item is found and then stop processing. If the flag item is missing then an exception needs to be raised.

Using the Python for...else construct you have

for i in mylist:
    if i == theflag:
        break
    process(i)
else:
    raise ValueError("List argument missing terminal flag.")

Compare this to a method that does not use this syntactic sugar:

flagfound = False
for i in mylist:
    if i == theflag:
        flagfound = True
        break
    process(i)

if not flagfound:
    raise ValueError("List argument missing terminal flag.")

In the first case the raise is bound tightly to the for loop it works with. In the second the binding is not as strong and errors may be introduced during maintenance.

2 of 16
428

It's a strange construct even to seasoned Python coders. When used in conjunction with for-loops it basically means "find some item in the iterable, else if none was found do ...". As in:

found_obj = None
for obj in objects:
    if obj.key == search_key:
        found_obj = obj
        break
else:
    print('No object found.')

But anytime you see this construct, a better alternative is to either encapsulate the search in a function:

def find_obj(search_key):
    for obj in objects:
        if obj.key == search_key:
            return obj

Or use a list comprehension:

matching_objs = [o for o in objects if o.key == search_key]
if matching_objs:
    print('Found {}'.format(matching_objs[0]))
else:
    print('No object found.')

It is not semantically equivalent to the other two versions, but works good enough in non-performance critical code where it doesn't matter whether you iterate the whole list or not. Others may disagree, but I personally would avoid ever using the for-else or while-else blocks in production code.

See also [Python-ideas] Summary of for...else threads

🌐
GeeksforGeeks
geeksforgeeks.org › python › using-else-conditional-statement-with-for-loop-in-python
Using Else with Loops in Python - GeeksforGeeks
In the case of array [1, 3, 5] the if is not executed for any iteration and hence the else after the loop is executed. ... # Python 3.x program to check if an array consists # of even number def contains_even_number(l): for ele in l: if ele % 2 == 0: print ("list contains an even number") break # This else executes only if break is NEVER # reached and loop terminated after all iterations.
Published   October 4, 2025
🌐
Programiz
programiz.com › python-programming › if-elif-else
Python if, if...else Statement (With Examples)
number = 5 # outer if statement if number >= 0: # inner if statement if number == 0: print('Number is 0') # inner else statement else: print('Number is positive') # outer else statement else: print('Number is negative') ... Here's how this program works. ... In certain situations, the if statement ...
🌐
Python Tips
book.pythontips.com › en › latest › for_-_else.html
21. for/else — Python Tips 0.1 documentation
for item in container: if search_something(item): # Found it! process(item) break else: # Didn't find anything.. not_found_in_container() Consider this simple example which I took from the official documentation:
🌐
Python documentation
docs.python.org › 3 › tutorial › controlflow.html
4. More Control Flow Tools — Python 3.14.6 documentation
When used with a loop, the else clause has more in common with the else clause of a try statement than it does with that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs. For more on the try statement and exceptions, see Handling Exceptions. The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example...
Find elsewhere
🌐
Tutorialspoint
tutorialspoint.com › python › python_forelse_loops.htm
Python for-else Loops
The following program shows how ... for i in ['T','P']: print(i) break else: # Loop else statement # terminated after 1st iteration due to break statement in for loop print("Loop-else statement successfully executed")...
🌐
Towards Data Science
towardsdatascience.com › home › latest › python for-else and while-else clearly explained with 4 real-world examples
Python For-Else and While-Else Clearly Explained with 4 Real-World Examples | Towards Data Science
March 5, 2025 - For a moment, stop trying to make sense of the wordelse`. Just think that Python is offering you an additional feature with its loops. Let us see how it works. ... The else clause will not be executed if the loop gets terminated by a break statement. If a loop does not hit a break statement, then the else clause will be executed once after the loop has completed all its iterations (meaning, after the loop has completed normally). Image by Author – For-Else and While-Else in Python
🌐
Study.com
study.com › computer science courses › computer science 113: programming in python
Else Statements in Loops in Python: Definition & Examples | Study.com
So, the break in the loop is never executed and therefore, the else clause is executed. There we print a message saying that the value of 2 was not found. To unlock this lesson you must be a Study.com member Create an account · If we had to do the above example without using the else clause, it would look something like this: #!/usr/bin/python found=False for i in [1,5,9]: print('In for') if i == 2: found=True break if not found: print('Duh!!
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-for-else
Python For Else - GeeksforGeeks
July 23, 2025 - In this example, the loop iterates over all elements in the numbers list and then execute the else block because no break the statement was encountered. ... numbers = [1, 2, 3, 4, 5] for num in numbers: print(num) else: print("Loop completed without encountering a break.")...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-if-else
Python If Else Statements - Conditional Statements - GeeksforGeeks
May 21, 2026 - Interview Questions · Examples · Quizzes · DSA Python · Data Science · NumPy · Pandas · Practice · Django · Flask · Last Updated : 21 May, 2026 · If-Else statements are conditional statements used to perform decision-making in a program. They allow different blocks of code to execute based on whether a condition is True or False.
🌐
Tutorial Teacher
tutorialsteacher.com › python › python-else-loop
Python else Loop
for x in range(5): print ("iteration no {} in for loop".format(x+1)) else: print ("else block in loop") print ("Out of loop") The output of the above code confirms that the else block in the for loop will be executed while the number is in the range.
🌐
Tutorialspoint
tutorialspoint.com › python › python_if_else.htm
Python if-else Statement
Now, let's see the Python implementation the above flowchart. age=25 print ("age: ", age) if age >=18: print ("eligible to vote") else: print ("not eligible to vote") On executing this code, you will get the following output − ... To test ...
🌐
Python Tutorial
pythontutorial.net › home › python basics › python for…else
Introduction to the Python for else statement - Python Tutorial
March 31, 2025 - The following example uses a for...else statement to iterate over a list and display that the list is empty: people = [] for person in people: print(person) else: print("The list is empty.")Code language: PHP (php) ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › if-else-statements-in-python
How to Use If/Else Statements in Python: A Beginner’s Guide | DigitalOcean
March 7, 2025 - ... temp = int(input("Enter the temperature: ")) if temp > 30 and temp < 40: print("It's a hot day!") else: print("It's not a hot day.") # Example using 'or' operator if temp > 30 or temp < 10: print("Temperature is extreme!") # Example using 'not' operator if not (temp > 30 and temp < 40): ...
🌐
Jerry Ng
jerrynsh.com › python-for-else-construct-a-deep-dive
How and When To Use For Else in Python Loop - Jerry Ng
April 3, 2023 - But, when would you use the for-else construct in Python? A common use case is to go through a loop until something is found. When we find what we want, we would then break out of the loop and handle that case accordingly. In short, we need to determine which case has happened: ... One common method is to create a flag variable that will let us do a check later to see how the loop was exited. Now, let’s take a look at an example...
🌐
Scaler
scaler.com › home › topics › python › python for else
Python For Else - Scaler Topics
December 1, 2023 - For-else and while-else are helpful features provided by Python. You can use the else block just after the for and while loop. Otherwise, the block will be executed only if a break statement doesn't terminate the loop.
🌐
Intoli
intoli.com › blog › for-else-in-python
Why Python's for-else Clause Makes Perfect Sense, but You Still Shouldn't Use It
August 28, 2018 - In Python, you can use the else keyword in for-else and while-else clauses, and not just the if-else clause. In this post, I describe how to use these controversial clauses, and explore how and why you might want to avoid using them.