enumerate() values starting at 1 vs. 0

python at bdurham.com python at bdurham.com
Wed May 14 16:10:24 EDT 2008


Arnaud,

>> Is there any way to have enumerate() start at 1 vs. 0?
>>
>> The problem with starting at 0 is that many things in the real world
>> begin at 1 - like line numbers or labels in a list.

> I suppose you could redefine enumerate to support an optional argument:
> 
> from itertools import izip, count
> 
> def enumerate(iterable, start=0):
>      return izip(count(start), iterable)
> 
>  >>> list(enumerate('spam', 1))
> [(1, 's'), (2, 'p'), (3, 'a'), (4, 'm')]

Brilliant!! 

Thank you,
Malcolm



More information about the Python-list mailing list