As a long-time Python lover, I now prefer Pony’s for/else construct which executes the else block if the for block did not execute at all.
It would be really nice for a language to have both.
This usage of the else keyword seems like an occasional useful but of semantic sugar, but dang, could they have at least chosen a different keyword? The word “else” makes absolutely no sense here! Fully exhausting a for loop doesn’t seem like an “else,” that seems like the normal usage of a for loop. In my opinion, it should have been called something like “then” to make it clear that it’s a continuation. Before I read this article, I assumed that the else keyword after a for loop would only execute if the loop never ran.
The most common use case is searching for a particular value using the for loop. If found, a break is then executed and the else block is skipped. If no value is found, the else block is executed. This makes “else” make a little more sense as the keyword.
Think of for/else like an if statement where the condition is evaluated multiple times. It’s basically just a more expressive version of:
if any(c for c in conditions):
# at least one condition is True
# no condition is True
In your mind, just replace for with if and it makes a sort of sense.
I can’t seem to find a link, but I vaguely remember Guido remarking that he wishes he’d named it “nobreak”, which makes a lot more sense for me.
Python is unfortunately heavy with syntax. Expressing for/else in a language like Haskell, Ocaml, and I assume Rust, is something more likely (and easily) done in a library.