all Python 3Lists (list)term
enumerate() with a list
iteration
enumerate() yields (index, item) pairs. start= sets the initial index.
Syntax
enumerate(lst[, start=0])
enumerate() is lazy: it returns an iterator, not a list, so printing the object shows <enumerate object ...> and a second pass over it yields nothing — wrap it in list() if you need all the pairs at once. The start= argument shifts the counter only, not the items: after enumerate(lst, 1) the value of i is no longer a valid index into lst.
Examples
lst = ['a', 'b', 'c']
for i, v in enumerate(lst):
print(i, v) # → 0 a / 1 b / 2 c
for i, v in enumerate(lst, start=1):
print(i, v) # → 1 a / 2 b / 3 c
print(list(enumerate(['x', 'y', 'z']))) # → [(0, 'x'), (1, 'y'), (2, 'z')]
words = ['zero', 'one', 'two']
print({i: w for i, w in enumerate(words)}) # → {0: 'zero', 1: 'one', 2: 'two'}
# Индекс максимального элемента
lst = [10, 30, 20]
print(max(enumerate(lst), key=lambda x: x[1])) # → (1, 30)
See also
Open in the full glossarydocs.python.orgReport an inaccuracy