A quirk/gotcha of for i, x in enumerate(seq) when seq is empty
Peter Otten
__peter__ at web.de
Fri Feb 24 07:44:15 EST 2012
Rick Johnson wrote:
> On Feb 23, 6:30 pm, Alex Willmer <a... at moreati.org.uk> wrote:
>> [...]
>> as a standard looping-with-index construct. In Python for loops don't
>> create a scope, so the loop variables are available afterward. I've
>> sometimes used this to print or return a record count e.g.
>>
>> for i, x in enumerate(seq):
>> # do stuff
>> print 'Processed %i records' % i+1
>
> You could employ the "else clause" of "for loops" to your advantage;
>>>> for x in []:
> ... print x
> ... else:
> ... print 'Empty Iterable'
> Empty Iterable
>
>>>> for i,o in enumerate([]):
> ... print i, o
> ... else:
> ... print 'Empty Iterable'
> Empty Iterable
No:
>>> 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.
More information about the Python-list
mailing list