Dovi
Dovi

Reputation: 15

Enumeration from 1

Is it possible to start counting number of iterations from 1 using enumerate function? If not, how to do it efficient way? There's particular piece of code I'm working with:

for nr, month in enumerate(range(1, 13)):
    print "Month: ", nr

I need to enumerate months from 1 to 12.

Upvotes: 0

Views: 66

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123520

Yes, simply tell enumerate() where to start; it takes a second argument for that:

for nr, month in enumerate(range(1, 13), 1):

From the enumerate() documentation:

enumerate(sequence, start=0)
[...] The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence

Bold emphasis mine.

Not that you really need it here, you are producing a range of numbers already, you can simply re-use month in this case as nr and month will always be equal now.

Upvotes: 1

Related Questions