3 ms·
Yes the for...else is useful but for years it didn't do what I expected, which is execute when the sequence was empty. After reading the docs a half dozen time
by mixmastamyk 8y ago
Yes the for...else is useful but for years it didn't do what I expected, which is execute when the sequence was empty. After reading the docs a half dozen times I finally internalized that the else actually means "not broken," aka "not found."
So now when I use it, I always put a comment next to it for myself and the next person:
for item in items:
if found:
break
else: # no-break
print('not found.')
- deleted 8y ago[deleted]
- deleted 8y ago[deleted]
- kazinator 8y agoIn fact, what it means is "execute this else when the loop guard fails" (regardless of whether the loop body has executed at all, or how many times). It is a legitimate alternate clause in the sense that it provides alternative behavior when the guard fails. Except when the loop is infinite, or is broken prematurely, the loop guard will fail. Under for item in list, the implicit guard fails immediately when the list is empty. If the list isn't empty, it fails after the last item is iterated upon. Thus here it also means "else if there are no more items to be processed".
- acqq 8y ago> It is a legitimate alternate clause in the sense that it provides alternative behavior when the guard fails. But the "guard fails" and the else is executed on every normal loop exit, except if the exit was done with break. for a in range( 1,3 ): print( a ) else: print( "end" ) gives: 1 2 end It's an "alternative" only when there's break. In all other cases it is executed. Even naming it "nobreak" would be confusing as without break it is always executed at the end. The clearer naming would be approximately "on_every_nonbreak_end_of_for"
- iamforreal 8y agoHonestly, I would just not use it wherever possible. It's a wart on the language, and there are plenty of semantically superior alternatives. I would rather wrap in function + use return over break, use a sentinel value, or raise an exception over using the else block. If there's anything I've learned, it's that just because a language has a feature, doesn't mean it should be used.
- maxbond 8y agoFunction + return seems like a good solution, but I'd rather not keep additional state or use `raise` (ie socially acceptable GOTO) when the language has a primitive for this. You shouldn't use a feature just because a language has it, you should use it because it's a simple, well-defined primitive that's less complex than alternatives.
- rplnt 8y ago> for years it didn't do what I expected, which is execute when the sequence was empty It does though http://codepad.org/en4mzowh http://codepad.org/en4mzowh
- mixmastamyk 8y agoSorry, "^only execute when the sequence was empty".