While in theory this is useful, it's one of the least intuitive parts of python for me. I avoid them whenever possible because I feel "else" conveys the intent very poorly. (And I've been writing python for years.)
What's more, it dances very close to something that is a super-common error for novice programmers: the early return from a loop. I grade AP exams every year, and one of the hands-down most common conceptual mistakes I've seen (on problems where this is relevant) goes something like this: boolean lookForSomething(int parameter) { for (Item item: list) { if (item.matches(parameter)) return true; else return false; } }…
The `else` there is superfluous; that cuts it down to this:
def look_for_something(parameter):
for item in list:
if matches(item, parameter):
return True
return False
And then after that one should just replace the entire loop with an `any` call: def look_for_something(parameter):
return any(matches(item, parameter) for item in list)
Also, if we assume a `matches()` that is simple equality, then it would just be def look_for_something(parameter):
return parameter in list
… and even then, you shouldn’t have named a variable `list`.Cut down to its essence like this, the function probably shouldn’t have even existed… ☺