Python enumerate and zip Exercises: Cleaner Loops
Most loop bugs come from bookkeeping: an index that drifts, a counter that starts at the wrong place, or two lists that silently stop matching. enumerate and zip put those relationships into the loop header where they are easier to see.
Let enumerate carry the index
The loop variable receives a pair, so unpack it into an index and an item. There is no counter to initialize and no increment to forget. The original list is unchanged.
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(index, color)Index and value in one loop
Choose a human-facing start
Computers usually count from zero, but people often expect one. The start argument changes only the numbering. It does not slice the list or skip the first item.
for number, color in enumerate(["red", "green"], start=1):
print(f"{number}: {color}")Numbering from one
Walk parallel lists with zip
zip pairs the first items, then the second items, and so on. It stops at the shortest input. Print list(zip(...)) while debugging so you can see the actual pairs instead of an iterator object.
names = ["Ada", "Grace"]
scores = [92, 88]
for name, score in zip(names, scores):
print(f"{name}: {score}")Two lists, one loop
Use strict zip when lengths must match
Silent truncation is convenient for some data and dangerous for others. Python 3.10 added strict=True, which raises ValueError when the inputs have different lengths. Use it when a missing row should be a visible error.
pairs = list(zip([1, 2], ["a", "b"], strict=True))
print(pairs)Fail loudly on mismatched data
Build a dictionary from two lists
dict accepts an iterable of key-value pairs, and zip produces exactly that shape. Check for duplicate keys first if the source data may contain them; later pairs win when dict sees the same key twice.
names = ["Ada", "Grace"]
scores = [92, 88]
print(dict(zip(names, scores)))Pairs become a mapping
Your practice checklist
- Use enumerate instead of a manual counter.
- Use start=1 for numbering shown to people.
- Remember that zip stops at the shortest input.
- Use strict=True when mismatched lengths are an error.
- Convert an iterator to a list when you need to inspect it.
Common questions
Does enumerate copy the list?
No. It returns an iterator that reads the existing iterable and produces index-item pairs.
Why does zip stop early?
zip ends as soon as any input is exhausted. That behavior lets it work with infinite iterators, but it can hide missing data.
Can I zip more than two lists?
Yes. zip accepts any number of iterables and produces tuples with one value from each.
Practice enumerate and zip
12 questions on indexes, parallel lists, strict zip, and dictionary construction.
Keep reading: