Behavior of the for-else construct
Chris Angelico
rosuav at gmail.com
Fri Mar 4 02:18:51 EST 2022
On Fri, 4 Mar 2022 at 18:13, Dieter Maurer <dieter at handshake.de> wrote:
>
> Rob Cliffe wrote at 2022-3-4 00:13 +0000:
> >I find it so hard to remember what `for ... else` means that on the very
> >few occasions I have used it, I ALWAYS put a comment alongside/below the
> >`else` to remind myself (and anyone else unfortunate enough to read my
> >code) what triggers it, e.g.
> >
> > for item in search_list:
> > ...
> > ... break
> > else: # if no item in search_list matched the criteria
> >
> >You get the idea.
> >If I really want to remember what this construct means, I remind myself
> >that `else` here really means `no break`. Would have been better if it
> >had been spelt `nobreak` or similar in the first place.
>
> One of my use cases for `for - else` does not involve a `break`:
> the initialization of the loop variable when the sequence is empty.
> It is demonstrated by the following transscript:
>
> ```pycon
> >>> for i in range(0):
> ... pass
> ...
> >>> i
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> NameError: name 'i' is not defined
> >>> for i in range(0):
> ... pass
> ... else: i = None
> ...
> >>> i
> >>>
> ```
>
> For this use case, `else` is perfectly named.
What's the point of this? Why not just put "i = None" after the loop?
ChrisA
More information about the Python-list
mailing list