Next / Previous / Contents / TCC Help System / NM Tech homepage

20.12. enumerate(): Step through indices and values of an iterable

Given an iterable S, enumerate(S) produces an iterator that iterates over the pairs of values (i, S[i]), for i having the values in range(len(S)). For more information on iterators, see Section 24.2, “Iterators: Values that can produce a sequence of values”.

>>> L = ['Ministry', 'of', 'Silly', 'Walks']
>>> for where, what in enumerate(L):
...     print "[{0}] {1}".format(where, what)
... 
[0] Ministry
[1] of
[2] Silly
[3] Walks

If you would like the numbers to start at a different origin, pass that origin as the second argument to the enumerate() function. You will still get all the elements of the sequence, but the numbers will start at the value you provide. (Python 2.6 and later versions only.)

>>> for where, what in enumerate(L, 1):
...     print "[{0}] {1}".format(where, what)
... 
[1] Ministry
[2] of
[3] Silly
[4] Walks