A quirk/gotcha of for i, x in enumerate(seq) when seq is empty

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Feb 24 15:54:22 CET 2012


On Fri, 24 Feb 2012 13:44:15 +0100, Peter Otten wrote:

>>>> for i in []:
> ...     pass
> ... else:
> ...     print "else"
> ...
> else
>>>> for i in [42]:
> ...     pass
> ... else:
> ...     print "else"
> ...
> else
>>>> for i in [42]:
> ...     break
> ... else:
> ...     print "else"
> ...
>>>>
>>>>
> The code in the else suite executes only when the for loop is left via
> break. A non-empty iterable is required but not sufficient.

You have a typo there. As your examples show, the code in the else suite 
executes only when the for loop is NOT left via break (or return, or an 
exception). The else suite executes regardless of whether the iterable is 
empty or not.


for...else is a very useful construct, but the name is misleading. It 
took me a long time to stop thinking that the else clause executes when 
the for loop was empty.

In Python 4000, I think for loops should be spelled:

for name in iterable:
    # for block
then:
    # only if not exited with break
else:
    # only if iterable is empty

and likewise for while loops.

Unfortunately we can't do the same now, due to the backward-incompatible 
change in behaviour for "else".



-- 
Steven



More information about the Python-list mailing list