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.
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.
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
elseclause, if present, is executed, and the loop terminates.A
breakstatement executed in the first suite terminates the loop without executing theelseclause’s suite. Acontinuestatement executed in the first suite skips the rest of the suite and continues with the next item, or with theelseclause 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")
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.