Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
The for/Else Statement in Python (theautomatic.net)
8 points by atreadw on July 9, 2020 | hide | past | favorite | 7 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.


The most common use case of for/else for me is:

for/len==0




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: