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

Alex Willmer alex at moreati.org.uk
Thu Feb 23 19:30:09 EST 2012

This week I was slightly surprised by a behaviour that I've not
considered before. I've long used

for i, x in enumerate(seq):
   # do stuff

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

However as I found out, if seq is empty then i and x are never
created. The above code will raise NameError. So if a record count is
needed, and the loop is not guaranteed to execute the following seems
more correct:

i = 0
for x in seq:
    # do stuff
    i += 1
print 'Processed %i records' % i

Just thought it worth mentioning, curious to hear other options/

More information about the Python-list mailing list