4 ms·
I agree that the use of else on for and while clauses is very not intuitive. It would be far better if the else would be executed if the list you're iterating o
by dudus 14y ago
I agree that the use of else on for and while clauses is very not intuitive. It would be far better if the else would be executed if the list you're iterating over is empty and thus the for/while clause is never ran not even once.
So you could rewrite:
last_val = None
for item in myList:
last_val = item
to:
for item in myList:
last_val = item
else:
last_val = None
- ggchappell 14y agoYes, "else" is a strange keyword to use for it, but I have found the existing semantics to be useful in practice. The application is nearly always related to handling success/failure of some kind of search. In Python, for..else allows elimination of variables whose names are something like "found". In C++: bool found = false; for (...) // Look for something { XXX; if (YYY) { found = true; break; } } if (!found) // Didn't find it { ZZZ; } but in Python: for ...: # Look for something XXX if YYY: break else: # Didn't find it ZZZ