If you want to start from another number, pass the number to the second argument of enumerate() . For example, this is useful when generating sequential number strings starting from 1. It is smarter to pass the starting number to the second argument of enumerate() than to calculate i + 1 .
Instead of using the range() function, we can instead use the built-in enumerate() function in python. enumerate() allows us to iterate through a sequence but it keeps track of both the index and the element. The enumerate() function takes in an iterable as an argument, such as a list, string, tuple, or dictionary.
What does enumerate do in Python? The enumerate function in Python converts a data collection object into an enumerate object. Enumerate returns an object that contains a counter as a key for each value within an object, making items within the collection easier to access.
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.
Just to put this here for posterity sake, in 2.6 the "start" parameter was added to enumerate like so:
enumerate(sequence, start=1)
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
Easy, just define your own function that does what you want:
def enum(seq, start=0):
for i, x in enumerate(seq):
yield i+start, x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With