Adds an additional start argument to the built-in enumerate function.
1 2 3 4 5 6 7 8 9
from itertools import izip, count def enumerate(a, b=None): "enumerate([start,] iterable)" if b is None: start, iterable = 0, a else: start, iterable = a, b return izip(count(start), iterable)
Presenting a more general solution to the loop counter problem "because sometimes you don't want to start counting from zero": <pre> for checknum, check in enumerate(lastchecknum, checks): printdraft(check, checknum)
myfile = open(myfilename) for lineno, line in enumerate(myfile): print '%4d: %s' % (lineno, line) </pre>
This should run just as fast as the built-in version of enumerate().
Why so complex?
Why not... Well, for one thing it takes about twice as long as the proposed solution would (if it wasn't buggy). On my system enumerating a list of 10000000 takes between 7.8 and 8.8 seconds with the solution described in the article versus 18 seconds with your solution. This is because you've introduced an extra layer of iterator.
return is incorrectly part of the 'else' clause.
Alternative. def enumerate(iterable, start=None): return izip(count(start or 0), iterable)
oops ! This was meant to be on two lines