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

Rick Johnson rantingrickjohnson at gmail.com
Fri Feb 24 07:32:29 EST 2012


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;
(psst: which coincidentally are working pro-bono in this down
economy!)

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




More information about the Python-list mailing list