[Python-ideas] for/else syntax

Gerald Britton gerald.britton at gmail.com
Fri Oct 2 15:46:38 CEST 2009


I can't imagine why I'm still commenting on this thread, since there
is no chance that Python will remove the "else" from for/while or put
conditions on it, but here is an example of a use that has no break
statement:

for i, j in enumerate(something):
  # suite
  i += 1
else:
  i = 0

# i == number of things processed

The thing here is, "i" won't be set by the "for" statement if
"something" is empty.  OTOH, if "something" is non-empty, i >= 1 at
the end of the for-loop.  Using the "else" clause in this way ensure
that "i" has the number of things processed at the end of the loop.

To do this without the "else" I have to:

i = 0
for i, j in enumerate(something):
  # suite
  i += 1
I can't imagine why I'm still commenting on this thread, since there
is no chance that Python will remove the "else" from for/while or put
conditions on it, but here is an example of a use that has no break
statement:

for i, j in enumerate(something):
  # suite
  i += 1
else:
  i = 0

# i == number of things processed

Does it work?  Sure!  But it moves the setting of "i" outside the
for-construct, which I personally dislike.

On Fri, Oct 2, 2009 at 8:58 AM, Michael Foord <fuzzyman at gmail.com> wrote:
>
>
> 2009/10/2 Yuvgoog Greenle <ubershmekel at gmail.com>
>>
>> I think I understand what you're saying and I just don't understand how it
>> pertains to for..else. Specifically I would like an explanation about why
>> the following quote is nonsense to you.
>
> Hmm... on consideration, breaking out of a loop without a break (i.e.
> exception or return) wouldn't enter the else clause *anyway*, so there is
> still no need for the else clause.
>
> My apologies, I retract. :-)
>
> Michael
>
>>>
>>> 2009/10/2 Stephen J. Turnbull <stephen at xemacs.org>
>>>
>>> Yuvgoog Greenle writes:
>>>
>>>  > 1. Not allowing a for loop that has no "break" to have an "else". Just
>>> like
>>>  > "else" isn't allowed when there isn't an "except" in the "try". There
>>> really
>>>  > is no excuse, justification or sense in a "for" loop that has no
>>> "break" yet
>>>  > has an "else".
>>>
>>> +1.  File an RFE against PyLint for sure, and against Python too.
>>> That's a *great* idea!
>>
>>
>
>
>
> --
> http://www.ironpythoninaction.com/
>
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
>



-- 
Gerald Britton



More information about the Python-ideas mailing list