Question

I need my counter to start at 1. Right now I have

for(counter, file) in enumerate(files):
    counter += 1
    //do stuff with file and counter

But there must be a better way, in Python v2.4

Was it helpful?

Solution

Instead of counter += 1, maybe use counter + 1 where you've used counter.

Alternatively:

for counter, file in ((i + 1, f) for i, f in enumerate(files)):
    ...

(Python 2.6 and later has some great stuff. Try to upgrade if you can.)

OTHER TIPS

Generators are perfect for this:

def altenumerate( it ):
    return ((idx+1, value) for idx, value in enumerate(it))

A simplified for older versions of python:

def altenumerateOld( it ):
    idx = 1
    for value in it:
        yield (idx, value)
        idx += 1

You can make your own version of enumerate():

def enumerate_1based(iterable):
    for index, item in enumerate(iterable):
        yield index+1, item

Alternately, add a start argument, to make it work just like later versions of enumerate().

You can use zip():

>>> enums = zip(range(1, len(files) + 1), files)
>>> for index, val in enums:
    print index, val

I did this like this:

#Emulate enumerate() with start parameter (introduced in Python 2.6)
for i,v in (i+start,v for i,v in enumerate(seq)):
    //do stuff

Basically, this is the same, yet a self-contained construct.

 for counter, item in enumerate(testlist):
    print(counter+1)
    print(item)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top