[Python-3000] else-clause on for-loops

Steven Bethard steven.bethard at gmail.com
Fri Mar 24 02:57:16 CET 2006


On 3/23/06, Ian Bicking <ianb at colorstudy.com> wrote:
> When I was just first learning Python I thought this would work:
>
>    for item in select_results:
>        ...
>    else:
>        ... stuff when there are no items ...
>
> But it doesn't work like that.

On 3/23/06, Brett Cannon <brett at python.org> wrote:
> I have to admit that is what I initially thought as well.  I think it
> is because when I read 'else' I viewed it as an alternative if the
> clause it was attached to didn't happen (ala an 'if' statement).

Yeah, I use for-else occasionally, and I know how it works in Python,
but every time I want to special-case the empty iterable case, I still
have to remind myself that the else-clause doesn't do what I want it
to.

There was talk previously_ about removing the else clause on for-loops
(and while-loops).  One possibility would be to change the else-clause
to behave as expected above (i.e. only executed when the loop fails to
iterate over any items).

I don't feel strongly on this one way or another -- I use the current
for-else syntax about as often as I need to special-case an empty
iterable.  Just thought I'd point out the old thread since it was
aimed at Python 3000-ish anyway.

.. previously: http://mail.python.org/pipermail/python-dev/2005-July/054695.html

STeVe
--
Grammar am for people who can't think for myself.
        --- Bucky Katt, Get Fuzzy


More information about the Python-3000 mailing list