Behavior of the for-else construct

Roel Schroeven roel at roelschroeven.net
Fri Mar 4 03:54:11 EST 2022


Op 4/03/2022 om 8:18 schreef Chris Angelico:
> On Fri, 4 Mar 2022 at 18:13, Dieter Maurer <dieter at handshake.de> wrote:
> > 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?
As I understand it: range(0) is just a (bad) example, it's actually 
about any arbitrary iterable. You don't know in advance if it's empty or 
not, and you want i to be initialized in all cases. (I don't think I 
have ever encountered that situation.)

You could easily solve this by placing "i = None" before the loop, but I 
guess in situations where you want to initialize i with the result of an 
expensive operation Dieter's method could be a reasonable solution.

This would actually be a good use case for computermaster360's proposal.

-- 
"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