Behavior of the for-else construct

gene heskett gheskett at shentel.net
Fri Mar 4 05:01:09 EST 2022


On Friday, 4 March 2022 02:18:51 EST Chris Angelico wrote:
> 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?
> 
That makes the logic work, but who then cleans up the trash on the stack.  
Thats a memory leak.

> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
> .


Cheers, Gene Heskett.
-- 
"There are four boxes to be used in defense of liberty:
 soap, ballot, jury, and ammo. Please use in that order."
-Ed Howdershelt (Author, 1940)
If we desire respect for the law, we must first make the law respectable.
 - Louis D. Brandeis





More information about the Python-list mailing list