https://book.pythontips.com/en/latest/for_-_else.html Answer from DismalActivist on reddit.com
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

🌐
W3Schools
w3schools.com › python › gloss_python_for_else.asp
Python For Else
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 »
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-else-loop
Python Else Loop - GeeksforGeeks
July 28, 2020 - We will use the same example as above but this time we will use for loop instead of while loop. ... 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.
🌐
Python Tips
book.pythontips.com › en › latest › for_-_else.html
21. for/else — Python Tips 0.1 documentation
for loops also have an else clause which most of us are unfamiliar with. The else clause executes after the loop completes normally. This means that the loop did not encounter a break statement. They are really useful once you understand where to use them.
🌐
Google Groups
groups.google.com › g › golang-nuts › c › 58DL23OOOPc
for { } else { }
But in any case, as with for else, they at most are only conveniences -- in this hypothetical switch continue case, you'd at most literally save one line of code (and it'd be backwards incompatible). In the for else case, you can always determine if the loop would have been broken out of by inverting the loop condition in a following if statement, taking effectively the same amount of code.
Find elsewhere
🌐
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
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.
🌐
Curiousefficiency
python-notes.curiousefficiency.org › en › latest › python_concepts › break_else.html
Else Clauses on Loop Statements - Alyssa Coghlan's Python Notes
While it’s not legal syntax, it may be helpful to mentally insert an except break: pass whenever you encounter a loop with an associated else clause in order to help remember what it means: for x in iterable: ... except break: pass # Implied by Python's loop semantics else: ...
🌐
Medium
medium.com › @andrewdass › python-for-loops-while-loops-and-if-else-statements-2ecc134953ca
Python: For Loops, While Loops and If-Else Statements | by Andrew Dass | Medium
February 12, 2024 - In this case, the if statement will not execute but the first elif statement would since the condition is satisfied and exit the entire if-else block, not executing the other statements that are afterward. If or any of the elif statements are not executed, then the else statement is always executed. ... In a for-loop, while loop or if-else statement, the “break” or “pass” statements can be used
🌐
Jerry Ng
jerrynsh.com › python-for-else-construct-a-deep-dive
How and When To Use For Else in Python Loop
April 3, 2023 - Here’s a trick to remember — the else in a for-else construct can be remembered as “no break”. It basically handles cases where no break statement is being executed within a loop.
🌐
Quora
quora.com › What-is-the-use-of-else-in-a-loop
What is the use of else in a loop? - Quora
Answer (1 of 5): Generally Loop statements are used for iterations that is doing any task again and again until any condition is true. Else statements is used to perform any task when given condition get false. Generally else statement is used with if statement (in most of the languages) but in ...
🌐
W3Schools
w3schools.com › java › java_for_loop.asp
Java For Loop
How Tos Add Two Numbers Swap Two ... Number ArrayList Loop HashMap Loop Loop Through an Enum ... assert abstract boolean break byte case catch char class continue default do double else enum exports extends final finally float for if implements import instanceof int interface ...
🌐
Plain English
python.plainenglish.io › python-up-your-code-else-in-loops-12ea62cef1a1
Python Up Your Code: Else … in loops
July 16, 2022 - Now, let’s dig a bit further into this. Does it still work if we break out of the loop? for i in range(3): print(i) break else: print("else block executed")Output: 0
🌐
DEV Community
dev.to › nomidlseo › mastering-pythons-loop-else-block-a-beginners-guide-to-for-and-while-loops-30je
Mastering Python’s Loop Else Block: A Beginner’s Guide to For and While Loops - DEV Community
November 6, 2025 - Under the hood, Python treats the else block in loops similarly to finally in try-except blocks, but with a focus on normal completion. ... So, conceptually, Python’s for-else and while-else are just syntactic sugar for a common “no break occurred” pattern — which is why they make code more readable.
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-use-else-conditional-statement-with-for-loop-in-python
How to use else conditional statement with for loop in python?
February 27, 2020 - while expr==True: #statements to be iterated while expr is true. else: #this statement(s) will be executed afteriterations are over · #this will be executed after the program leaves loop body · for x in range(6): print (x) else: print ("else block of loop") print ("loop is over")
🌐
GeeksforGeeks
geeksforgeeks.org › python › using-else-conditional-statement-with-for-loop-in-python
Using Else with Loops in Python - GeeksforGeeks
The else block just after for/while is executed only when the loop is NOT terminated by a break statement.
Published   October 4, 2025
🌐
Python
wiki.python.org › moin › ForLoop
ForLoop
Like the while loop, the for loop can be made to exit before the given object is finished. This is done using the break statement, which will immediately drop out of the loop and continue execution at the first statement after the block. You can also have an optional else clause, which will ...
🌐
freeCodeCamp
freecodecamp.org › news › for-else-loop-in-python
How Does Python's For-Else Loop Construct Work?
June 19, 2024 - The for loop iterates over each item in the iterable. If the condition is True and the control breaks out of the loop, the else block is skipped.
🌐
Tutorialspoint
tutorialspoint.com › python › python_forelse_loops.htm
Python for-else Loops
If the loop completes without encountering a break statement, the code in the else block is executed. The following program shows how else conditions works in case of break statement and conditional statements. # creating a function to check whether the list item is a positive # or a negative number def positive_or_negative(): # traversing in a list for i in [5,6,7]: # checking whether the list element is greater than 0 if i>=0: # printing positive number if it is greater than or equal to 0 print ("Positive number") else: # Else printing Negative number and breaking the loop print ("Negative number") break # Else statement of the for loop else: # Statement inside the else block print ("Loop-else Executed") # Calling the above-created function positive_or_negative()