The for/Else Statement in Python(theautomatic.net)
theautomatic.net
The for/Else Statement in Python
http://theautomatic.net/2020/07/09/the-for-else-statement-in-python/
8 comments
Surprising. I didn't know this construct and I would naturally assume that the else part would execute if the loop never spun (because the list/etc was empty)
Yes, the else keyword is not intuitive. The best way to remember for/else is for/nobreak
Right! nobreak would make it much clearer.
It would involve adding a new keyword to the language though. I imagine there was some desire to avoid that.
This was my guess too.
Relatedly there's also a try/else, where the else block only runs if there wasn't an exception.
All these else variants come in handy from time to time.
All these else variants come in handy from time to time.
[deleted]
The most common use case of for/else for me is:
for/len==0
for/len==0