enumerate()
enumerate() gives you each item of a sequence together with its position, so you don't have to keep a counter by hand.
Used in 24 lessons of the course, from 00.01.
enumerate(items) walks through items and on each turn produces a tuple (index, item). That's why you write two names in the for: for i, item in enumerate(items):. Python unpacks the tuple into i and item.
By default it counts from 0, like list indexes. If you want numbering for people, pass the keyword argument start=1. In lesson 00.01 you'll see for number, term in enumerate(quiz_terms, start=1):, which numbers the questions 1, 2, 3…
Why not range(len(items))? Because with enumerate() you read the item directly, without items[i]. The code is shorter and it's harder to get the indexes wrong.
Reach for it when: inside a for loop, you need both the item and its position, for example to number a list.
Examples
Common mistake
names = ["Ana", "Luis"]
for name in enumerate(names):
print(name)Why: With a single name in the for, you get the whole tuple, not just the item.
How to write it: Use two names to unpack: for i, name in enumerate(names):
Common mistake
names = ["Ana", "Luis"]
for name, i in enumerate(names):
print(i, name)Why: The order is swapped: enumerate() always gives the index first and the item second.
How to write it: Put the index first: for i, name in enumerate(names):
