How to enumerate a range of numbers starting at 1

I am using Python 2.5, I want an enumeration like so (starting at 1 instead of 0):

[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]

I know in Python 2.6 you can do: h = enumerate(range(2000, 2005), 1) to give the above result but in python2.5 you cannot...

Using Python 2.5:

>>> h = enumerate(range(2000, 2005))
>>> [x for x in h]
[(0, 2000), (1, 2001), (2, 2002), (3, 2003), (4, 2004)]

Does anyone know a way to get that desired result in Python 2.5?


Solution 1:

As you already mentioned, this is straightforward to do in Python 2.6 or newer:

enumerate(range(2000, 2005), 1)

Python 2.5 and older do not support the start parameter so instead you could create two range objects and zip them:

r = xrange(2000, 2005)
r2 = xrange(1, len(r) + 1)
h = zip(r2, r)
print h

Result:

[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]

If you want to create a generator instead of a list then you can use izip instead.

Solution 2:

Just to put this here for posterity sake, in 2.6 the "start" parameter was added to enumerate like so:

enumerate(sequence, start=1)

Solution 3:

Python 3

Official Python documentation: enumerate(iterable, start=0)

You don't need to write your own generator as other answers here suggest. The built-in Python standard library already contains a function that does exactly what you want:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

The built-in function is equivalent to this:

def enumerate(sequence, start=0):
  n = start
  for elem in sequence:
    yield n, elem
    n += 1