0

How does the else: condition work after a for loop in Python? I thought that else can work only after an if condition.

for i in range(5):
     print(i)
else:
    print("done")

I don't know how or why it works.

2

1 Answer 1

4

The else clause of a for loop is executed if the loop terminates because the iterator is exhausted, i.e., if a break statement is not used to exit the loop. From the documentation:

When the iterator is exhausted, the suite in the else clause, if present, is executed, and the loop terminates.

A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there is no next item.

Compare

for i in range(5):
    pass
else:
    print("Iterator exhausted")

with

for i in range(5):
    break
else:
    print("Iterator exhausted")
Sign up to request clarification or add additional context in comments.

1 Comment

I recall reading somewhere that the idea of such a finalizing clause in a for loop is due to Knuth, the choice of else as the keyword being that the break statement would virtually always guarded by an if statement, and the else clause being executed if the condition is never executed. I am not aware of other languages implementing such a feature prior to Python, though, nor can I find a citation for Knuth as the inventor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.