enumerate()
Getting the position alongside the item, without maintaining a counter or indexing back into the list.
Overview
The two things it replaces
The counter:
i = 0
for name in names:
print(i, name)
i += 1
and the index:
for i in range(len(names)):
print(i, names[i])
Both work. The first has a variable to initialise and remember to increment; forget the increment and the loop runs forever printing zero. The second reads the list twice per pass — once for the length, once per lookup — and puts names[i] where you wanted name.
for i, name in enumerate(names):
says the same thing with neither problem.
enumerate.py
enumerate_uses.py
Worth knowing
enumerate yields (index, item) tuples; the for unpacks them.start=1 changes the number it reports, not where it reads from.for i in range(len(x)) is the pattern this replaces.