Behavior of the for-else construct

Grant Edwards grant.b.edwards at gmail.com
Thu Mar 3 11:58:46 EST 2022


On 2022-03-03, computermaster360 <computermaster360 at gmail.com> wrote:

> Do you find the for-else construct useful?

Yes.

> Have you used it in practice?

Yes.

I don't use it often, but I do use it occasionally.

However, I always have to look it up the docs to confirm the logic. I
always feel like the else should be executed if the for loop does
_not_ terminate naturally, but it's the opposite.

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

That also make sense.

> 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).




More information about the Python-list mailing list