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
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
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
Benefits of using for else syntax
Consider the following code: found = False for username in userList: if username == userInput: found = True checkPassword(username) break if not found: doSomething() I have just learnt about the for...else... syntax, what are the benefits of using for...else... syntax? More on discuss.python.org
🌐 discuss.python.org
15
0
August 26, 2023
For-Else: A Weird but Useful Feature in Python
Just stay away from this feature. Treat it like javascript's ==. Python's For/Else is widely considered a huge mistake due to how counterintuitive the behavior is, as well as how trivially easy it is to substitute almost any for/else usage with something short and concise. Most linters are already configured to warn about for/else. More on reddit.com
🌐 r/programming
71
76
November 10, 2022
for...else???
A python core developer explains this [here] ( http://www.youtube.com/watch?v=OSGv2VnC0go&t=15m52s ). More on reddit.com
🌐 r/Python
21
12
July 24, 2017
🌐
W3Schools
w3schools.com › python › gloss_python_for_else.asp
Python For Else
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... 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 Yourself »
🌐
W3Schools
w3schools.com › python › python_if_else.asp
Python Else Statement
Python Examples Python Compiler ... Q&A Python Bootcamp Python Training ... The else keyword catches anything which isn't caught by the preceding conditions....
🌐
Python Tips
book.pythontips.com › en › latest › for_-_else.html
21. for/else — Python Tips 0.1 documentation
for n in range(2, 10): for x in range(2, n): if n % x == 0: print(n, 'equals', x, '*', n/x) break · It finds factors for numbers between 2 to 10. Now for the fun part. We can add an additional else block which catches the numbers which have no factors and are therefore prime numbers:
🌐
freeCodeCamp
freecodecamp.org › news › for-else-loop-in-python
How Does Python's For-Else Loop Construct Work?
June 19, 2024 - In this tutorial, we’ll learn how to use for-else loops by coding a couple of examples to understand how they work. In Python, the for-else loop is a construct that combines a for loop with an else clause.
🌐
Tutorialspoint
tutorialspoint.com › python › python_forelse_loops.htm
Python for-else Loops
Following is the syntax of for loop with optional else block − · for variable_name in iterable: #stmts in the loop . . . else: #stmts in else clause .
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-for-else
Python For Else - GeeksforGeeks
July 23, 2025 - By understanding and utilizing this construct, you can write more expressive and intentional Python code. The for else loop in Python allows you to execute a block of code when the for loop completes its iteration normally (i.e., without ...
🌐
Python documentation
docs.python.org › 3 › tutorial › controlflow.html
4. More Control Flow Tools — Python 3.14.6 documentation
If the loop finishes without executing the break, the else clause executes. In a for loop, the else clause is executed after the loop finishes its final iteration, that is, if no break occurred.
🌐
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 - To summarize, the else clause in Python provides a way to execute code after a loop has completed execution without encountering a break statement. I owe my thanks to this great talk by Raymond Hettinger, titled “Transforming Code into Beautiful, Idiomatic Python”. In the talk, he briefly spoke about the history of the for-else construct.
🌐
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
🌐
Scaler
scaler.com › home › topics › python › python for else
Python For Else - Scaler Topics
December 1, 2023 - The 'else' block in a 'for loop' in Python, often referred to as 'for else python', is executed after the for loop completes its iteration over the entire sequence, but only if a break statement didn't terminate the loop.
🌐
Python Tutorial
pythontutorial.net › home › python basics › python for…else
Introduction to the Python for else statement - Python Tutorial
March 31, 2025 - for item in iterables: # Process ... language: PHP (php) ... Python will execute the else block only if the for loop iterates all items in the iterables without hitting a break statement....
🌐
Codefinity
codefinity.com › courses › v2 › a8aeafab-f546-47e9-adb6-1d97b2927804 › 67140d04-48dc-4e46-b3fb-fcdf181555ec › 9d957f31-6156-480e-badf-4bce357b1e8a
Learn The Else Statement in a for Loop | The For Loop
Thanks for your feedback! Section 1. Chapter 5 ... In Python, the else statement can be used with a for loop. The else block executes when the loop completes all its iterations without being interrupted by a break statement.
🌐
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 - This might be straying further from the actual internal implementation of for-else loops, but it makes the analogy with for-else fairly clear. In both cases, we run the code from the else block when the condition that continues the loop becomes falsey. While loop-else has a perfectly reasonable explanation and can cut down on some boilerplate, you should still avoid using it if possible. The simple reason is that it can often be easily replaced by more fundamental and universally understandable Python constructs.
🌐
Tutorial Teacher
tutorialsteacher.com › python › python-else-loop
Python else Loop
The program exits the loop only after the else block is executed. ... for x in range(5): print ("iteration no {} in for loop".format(x+1)) else: print ("else block in loop") print ("Out of loop")
🌐
Python.org
discuss.python.org › python help
Benefits of using for else syntax - Python Help - Discussions on Python.org
August 26, 2023 - Consider the following code: found = False for username in userList: if username == userInput: found = True checkPassword(username) break if not found: doSomething() I have just learnt a…
🌐
Python Snacks
pythonsnacks.com › p › python-for-else-statement
A quick tutorial for the for/else construct in Python
April 15, 2025 - In the code snippet above, we search for the word “orange” in the items list. If we find it, we print a success message and exit the loop with break. However, if the loop completes without finding “orange”, the else block runs, printing a message that the item was not found. Going back to the semi-early days of your Python learning, you learned about control flow.
🌐
Reddit
reddit.com › r/programming › for-else: a weird but useful feature in python
r/programming on Reddit: For-Else: A Weird but Useful Feature in Python
November 10, 2022 - You use for/else because it's more concise, and because it's idiomatic Python. Linters don't warn about using it. Pylint has a warning for using for/else when the else clause is superfluous. Flake8 doesn't even have any rules for for/else. ... stuff = None for thing in collection: if has_some_property_we_care_about(thing) and not stuff: stuff = thing if not stuff: raise ValueError('we never found stuff to work on')