for x in li:
if x == to_find:
print("found")
break
else:
print("not found")
Logically, the "else" matches with the "if" introducing the "break" and means "if none of elements cause the break branch to be taken". for x in li:
if x == to_find:
print("found")
break
else:
print("not found")
Logically, the "else" matches with the "if" introducing the "break" and means "if none of elements cause the break branch to be taken". for x in sorted_list:
if x == to_find:
print("found")
break # we've found a match
elif to_find > x:
break # match is not possible
else:
print("not found)Also, nice counterexample.
First of all, the core of a linear search loop always has two exits: the break and the normal (unsuccessful) loop exit.
But in a lookup-or-insert pattern, a regular for loop has two possible states that the system can be in at the end of the loop. With a for-else loop, you can put the or-insert part into the else block, so that there is a simpler invariant: after the loop construct, the element always exists and has been found.
I was honestly surprised by all the negativity in this thread. To offer an alternative opinion, there have been plenty of times when I missed having for-else while writing C.
Python is probably not as simple as some like to claim, but this is not really any kind of special case. To have a special case, you need to have a normal-case behavior that is then broken: for instance, a function f(n) that "computes the factorial of n, unless if n is 1 in which case it returns 42" contains a special case, because n = 1 used to have a normal-case behavior of f(1) = 1. Special cases require the user to learn of its existence, or they will be bitten by it.
In this case, there isn't any special-casing: the support for "else" after a "for" block doesn't have any predetermined "normal-case" behavior. In most other languages, such a construct is simply not supported. Python adds a new behavior here without breaking any existing behavior.