Behavior of the for-else construct

Jon Ribbens jon+usenet at unequivocal.eu
Thu Mar 3 09:47:19 EST 2022


On 2022-03-03, computermaster360 <computermaster360 at gmail.com> wrote:
> Do you find the for-else construct useful? Have you used it in
> practice?

Yes, I use it frequently.

> I have used it maybe once. My issue with this construct is that
> calling the second block `else` doesn't make sense; a much more
> sensible name would be `then`.

You are not the only person with this opinion, although personally
I have the opposite opinion. I think of 'for...else' as being
a search for something that matches a condition, and the 'else'
block is if no item is found that matches. If you think of it like
that, the syntax makes perfect sense.

> Now, imagine a parallel universe, where the for-else construct would
> have a different behavior:
>
>     for elem in iterable:
>         process(elem)
>     else:
>         # executed only when the iterable was initially empty
>         print('Nothing to process')
>
> Wouldn't this be more natural? I think so. Also, I face this case much
> more often than having detect whether I broke out of a loop early
> (which is what the current for-else construct is for).

I guess peoples' needs vary. I can't even remember the last time
I've needed something as you suggest above - certainly far less
often than I need 'for...else' as it is now.

> What are your thoughts? Do you agree?

I don't agree. But it doesn't really matter if anyone agrees or not,
since there is no chance whatsoever that a valid Python syntax is
suddenly going to change to mean something completely different, not
even in "Python 4000" or whatever far-future version we might imagine.

This exact topic was discussd in November 2017 by the way, under the
subject heading "Re: replacing `else` with `then` in `for` and `try`".
I'm not sure any particular conclusion was reached though except that
some people think 'else' is more intuitive and some people think
'then' would be more intuitive.


More information about the Python-list mailing list