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

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
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
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
Examples of the while...else or for...else constructs in the wild?
I use a for/else in my code for a Miller-Rabin primality checker: def isPrime(n, k=5): # miller-rabin if n < 2: return False for p in [2,3,5,7,11,13,17,19,23,29]: if n % p == 0: return n == p s, d = 0, n-1 while d % 2 == 0: s, d = s+1, d/2 for i in range(k): x = pow(randint(2, n-1), d, n) if x == 1 or x == n-1: continue for r in range(1, s): x = (x * x) % n if x == 1: return False if x == n-1: break else: return False return True More on reddit.com
🌐 r/Python
34
13
November 13, 2014
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
🌐
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.
🌐
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:
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.
🌐
Jerry Ng
jerrynsh.com › python-for-else-construct-a-deep-dive
How and When To Use For Else in Python Loop
April 3, 2023 - It often confuses even seasoned Python programmers. 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.
🌐
freeCodeCamp
freecodecamp.org › news › for-else-loop-in-python
How Does Python's For-Else Loop Construct Work?
June 19, 2024 - If the condition is True, the control breaks out of the loop. The else block will execute only when the for loop completes normally without encountering a break statement. ... The for loop iterates over each item in the iterable.
🌐
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()
🌐
Medium
medium.com › nerd-for-tech › mastering-the-python-for-else-loop-cc8aa48083b7
Mastering the for-else loop in Python | by Allwin Raju | Nerd For Tech | Medium
December 2, 2024 - The for-else loop in Python has a unique behaviour. In this structure, the else block only executes if the loop completes normally without hitting a break statement.
🌐
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!!
🌐
Programiz
programiz.com › python-programming › if-elif-else
Python if, if...else Statement (With Examples)
You will get an error if you write ... statement. In this case, Python thinks our if statement is empty, which results in an error. An if statement can have an optional else clause....
🌐
Sololearn
sololearn.com › en › Discuss › 2336541 › solved-how-to-use-for-loop-and-if-statement-in-one-line
[solved] How to use for loop and if statement in one line??
Sololearn is the world's largest community of people learning to code. With over 25 programming courses, choose from thousands of topics to learn how to code, brush up your programming knowledge, upskill your technical ability, or stay informed about the latest trends.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-for-else
Python For Else - GeeksforGeeks
July 23, 2025 - Here’s a basic example to illustrate the for-else loop: 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.
🌐
Google Groups
groups.google.com › g › golang-nuts › c › 58DL23OOOPc
for { } else { }
In my experience, extracting such a loop into a function that returns a boolean instead of break usually improves readability. Then the else case is simply the code after the loop. On Sep 15, 2012 10:00 AM, "Nick Craig-Wood" <ni...@craig-wood.com> wrote: I'm missing the for else construct that I used to use in Python (and FORTH before that).
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-else-loop
Python Else Loop - GeeksforGeeks
July 28, 2020 - The else block just after for/while is executed only when the loop is NOT terminated by a break statement. In the following example, the else statement will only be executed if no element of the array is even, i.e. if statement has not been ...
🌐
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 - Just like a try block's else clause is only reached if no exceptions are raised, a for block's else clause is reached only if the loop isn't broken. It makes sense. ... Finally doesnt make sense though. Finally defines a block that should always run, regardless of what happens in the try block. An else does not always run. ... The oldest Python version for which I could find a reference is 1.1: https://www.python.org/ftp/python/doc/1.1/quick-ref.1.1.html.
🌐
Python documentation
docs.python.org › 3 › reference › compound_stmts.html
8. Compound statements — Python 3.14.6 documentation
The first item provided by the iterator is then assigned to the target list using the standard rules for assignments (see Assignment statements), and the suite is executed. This repeats for each item provided by the iterator. When the iterator is exhausted, the suite in the else clause, if present, is executed, and the loop terminates.
🌐
Python Morsels
pythonmorsels.com › for-else
Using "else" with a loop in Python - Python Morsels
April 19, 2026 - If you ever see an else block on a loop, now you know that it's not a typo. It's just a somewhat obscure Python feature. The else clause works on both for loops and while loops in Python.