Welcome, guest | Sign In | My Account | Store | Cart

Adds an additional start argument to the built-in enumerate function.

Python, 9 lines
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().

5 comments

Jean-Paul Calderone 19 years, 6 months ago  # | flag

Why so complex?

def enumerate(iterable, start=0, enumerate=enumerate):
    for idx, obj in enumerate(iterable):
        yield idx + start, obj
B. Smith-Mannschott 19 years, 6 months ago  # | flag

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.

B. Smith-Mannschott 19 years, 6 months ago  # | flag

return is incorrectly part of the 'else' clause.

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)
Louis RIVIERE 16 years, 8 months ago  # | flag

Alternative. def enumerate(iterable, start=None): return izip(count(start or 0), iterable)

Louis RIVIERE 16 years, 8 months ago  # | flag

oops ! This was meant to be on two lines

Created by Raymond Hettinger on Thu, 7 Oct 2004 (PSF)
Python recipes (4591)
Raymond Hettinger's recipes (97)

Required Modules

Other Information and Tasks