Python enumerate(): Loop with Index and Value
enumerate() gives you the position (index) and the value as a pair, one at a time, as you loop over a list. You don't need to make a separate counter variable and add 1 to it. The index starts at 0, and you can change that with start.
for index, value in enumerate(iterable, start=0):
Getting the index and the value together
Write two variables after for. The first one gets the index and the second one gets the value.
names = ["kim", "lee", "park"]for i, name in enumerate(names): print(i, name)0 kim 1 lee 2 park
start: counting from 1
Numbers you show to people usually start at 1. With start=1, only the numbering starts at 1, and the values still come from the first one as before. It does not skip the beginning of the list.
menu = ["soup", "rice", "tea"]for no, item in enumerate(menu, start=1): print(f"{no}. {item}") for no, ch in enumerate("ab", 10): print(no, ch)1. soup 2. rice 3. tea 10 a 11 b
Leaving out start= and writing just enumerate(menu, 1) with a second argument is the same. You can pass anything a for can loop over, such as a string.
Compared with range(len())
The result is the same as code that loops by index and gets the value with a[i]. The enumerate version is shorter because it has no line that fetches the value, and there is less chance of using the wrong index.
a = ["x", "y", "z"]for i in range(len(a)): print(i, a[i]) for i, v in enumerate(a): print(i, v)0 x 1 y 2 z 0 x 1 y 2 z
Use range(len(a)) when you need only the index, for v in a when you need only the value, and enumerate when you need both.
Finding the positions that match a condition
It fits well when you look for positions by value, as in "at which positions is the largest value?" index() tells you only the first one, but this way finds them all.
scores = [70, 95, 80, 95]best = max(scores)where = [i for i, s in enumerate(scores) if s == best]print(best, where)print(scores.index(best))print(list(enumerate("abc")))95 [1, 3] 1 [(0, 'a'), (1, 'b'), (2, 'c')]
Wrap it in list() as in the last line and you can see that what enumerate gives is (index, value) tuples.
Using it with zip
When you loop over two lists side by side and need the index too, write enumerate(zip(...)). Here the pair that zip gives has to be received inside parentheses.
names = ["kim", "lee"]scores = [90, 75]for rank, (name, score) in enumerate(zip(names, scores), 1): print(rank, name, score)1 kim 90 2 lee 75
Common mistakes
Receiving it in one variable
for x in enumerate(["a", "b"]):
print(x)
→ You get a whole tuple like (0, 'a'), not the value
Unpack it into two variables, as in for i, x in enumerate(...).
Swapping the order of index and value
for name, i in enumerate(["kim", "lee"]):
print(name, i)
→ With no error, name gets the index and i gets the name
The order is always index first, value second: for i, name in enumerate(...). Because there is no error, it shows up later as a strange result.
Reading list items with an index from start=1
a = ["x", "y", "z"]
for i, v in enumerate(a, start=1):
print(a[i])
→ Prints y and z, then IndexError: list index out of range
start changes only the number you show. The real index of the list still starts at 0, so you are off by one item each time. Use v for the value, and if you need to change an item, count from 0 without start.
Leaving out the parentheses with zip
for i, a, b in enumerate(zip([1, 2], [3, 4])):
print(i, a, b)
→ ValueError: not enough values to unpack (expected 3, got 2)
What enumerate gives is always two things, (index, value). When the value is a pair, unpack it once more with parentheses, as in for i, (a, b) in ....