Show a for-else block where the else clause runs because the loop completed without a break.
The else clause on a for loop is not the same else as the one in an if statement. It does not run when the loop finds nothing. It runs when the loop finishes normally, which means that it was never interrupted by a break.
def find_index(items, target):
for index, item in enumerate(items):
if item == target:
return index
else:
return -1
print(find_index(['a', 'b', 'c'], 'b')) # 1
print(find_index(['a', 'b', 'c'], 'z')) # -1
For the first call the loop finds b at index 1 and returns straight away, so the else clause is never reached. For the second call the loop runs through every item without matching anything, no break happens, and the else clause runs and returns -1.
The way it works is that a break statement suppresses the else clause. If you write a loop with a break for any reason other than finding the thing that you are looking for, then the else clause will quietly not run, and that is the one trap to be aware of.
The pattern is worth knowing because it removes the flag variable. The conventional version of this function needs a found = -1 line before the loop, an if inside it, and a return after it. Here the two ways out sit next to each other, and each one is a single return statement, so the function reads from the top to the bottom without an extra variable to keep track of.