[Python-Dev] Adding start to enumerate()

Steven D'Aprano steve at pearwood.info
Tue May 13 20:53:06 CEST 2008


On Wed, 14 May 2008 12:25:01 am Guido van Rossum wrote:

> However I see no use for skipping items
> from the start, 

You've never had to deal with data where the first N items were special 
in some way? e.g. skipping over a header line in a file?

I know I've written code like this before:

it = iter(whatever())
for i in xrange(N):  # skip the first N items
    it.next()
for item in it:
    process(item)


> and if that use case ever came up, passing a slice to 
> enumerate() would be the appropriate thing to do.

While slices are wonderfully useful things, they aren't panaceas. 
They're not so useful with iterators, and they make a copy of the data, 
which can be problematic if there's a *lot* of it.

[tongue firmly in cheek]
Perhaps what we need is a more flexible enumerate function?
enumerate(iterable, start_at_index=0, count_from=0)


Having a consistent index provided by enumerate reduces the amount of 
thought I have to put into the loop structure, and avoids the 
temptation to do this:

for i, item in enumerate(seq, start=1):
    print "line %d: %s" % (i, item)
    # subtract one from the index to adjust for one-based counting
    seq[i-1] = foo(item)

I never need to think about whether it is zero-based, one-based, or some 
other N-based counting, because it is always zero-based.

-0 on any change to enumerate.


-- 
Steven D'Aprano


More information about the Python-Dev mailing list