Behavior of the for-else construct
Roel Schroeven
roel at roelschroeven.net
Fri Mar 4 04:05:44 EST 2022
Op 4/03/2022 om 1:43 schreef Chris Angelico:
> Think of it like this:
>
> for item in search_list:
> if condition: pass
> else:
> print("Condition not true for this item")
>
> for item in search_list:
> if condition: break
> else:
> print("Condition not true for any item")
>
> There's a parallel here. Since a for-else loop is basically useless
> without an if-break construct inside it, the else clause can be
> thought of as the else on a massive if/elif chain:
>
> if stuff[0].is_good:
> print("This item is good", stuff[0])
> elif stuff[1].is_good:
> print("This item is good", stuff[1])
> ...
> ...
> elif stuff[n].is_good:
> print("This item is good", stuff[n])
> else:
> print("All items are bad")
>
> As a loop, this looks like this:
>
> for item in stuff:
> if item.is_good:
> print("This item is good", item)
> break
> else:
> print("All items are bad")
>
> The else is attached to the for so that it compasses ALL the if
> statements, but it's still broadly saying "do this when we don't hit
> the 'if' condition".
>
> Whether that's a sufficient mnemonic, I don't know [...]
Certainly not for me. It could work for the specific use case you
mention, but nothing in the definition restricts it to be used for that
use case. As Rob Cliffe says in one of his posts, a for-loop can be
terminated with "break" for many conceptually different reasons. A
mnemonic that only works for one specific use case, even if it's the
most used one, doesn't work as a mnemonic for the general concept for me.
> [...], but it doesn't
> really matter; the construct is useful to those of us who want it, and
> if other people ignore it, that's fine. Nobody ever said you had to
> use or understand every single feature of the language you're using.
True, still, I agree with people who think nobreak would have been
better because it better conveys the intention. IIRC Raymond Hettinger
once said something like that too, so I'm in good company I guess.
--
"Honest criticism is hard to take, particularly from a relative, a friend,
an acquaintance, or a stranger."
-- Franklin P. Jones
More information about the Python-list
mailing list