enumerate & zip
Published by Brayan K
Two tiny built-in functions fix two of the most common looping headaches: "I need the index and the item" and "I have two lists I want to walk together". enumerate() and zip() make both of these clean, readable, and bug-free.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Each round of the loop gets one pair
Loops - For and While ended with enumerate(), which counts the items as it goes, and zip(), which walks two lists side by side. Each round of the loop gets one pair, a tuple, and the for line unpacks it into two names. Print the pair itself and you can see it:
for pair in enumerate(["tea", "jam"]):
print(pair)
for pair in zip(["tea", "jam"], [3, 4]):
print(pair)
# ✅ Expected output:
# (0, 'tea')
# (1, 'jam')
# ('tea', 3)
# ('jam', 4)enumerate() puts the count first and the item second; zip() keeps the order you gave it the lists in. Name the two halves the wrong way round and nothing complains, because names are only names:
for name, place in enumerate(["tea", "jam"]):
print(f"{name} is in place {place}")
# ✅ Expected output:
# 0 is in place tea
# 1 is in place jamThe loop calls the count name and the item place. Python can't know; only the printed sentence gives it away.
A pair inside a pair
zip() takes three or more lists too, and each round then gets one item from each:
names = ["Ada", "Ben"]
maths = [90, 72]
science = [84, 95]
for name, m, s in zip(names, maths, science):
print(name, m, s, (m + s) / 2)
# ✅ Expected output:
# Ada 90 84 87.0
# Ben 72 95 83.5Putting zip() inside enumerate() gives each round a count and a pair, as in (1, ("Ada", 88)). That's two things, not three, so three names in the for line don't fit:
names = ["Ada", "Ben"]
scores = [88, 72]
for place, name, score in enumerate(zip(names, scores), start=1):
print(place, name, score)
# ✅ Expected error:
# ValueError: not enough values to unpack (expected 3, got 2)Brackets around the inner two names unpack the pair inside the pair, the way Tuples unpacks one level:
names = ["Ada", "Ben"]
scores = [88, 72]
for place, (name, score) in enumerate(zip(names, scores), start=1):
print(place, name, score)
# ✅ Expected output:
# 1 Ada 88
# 2 Ben 72The same goes for a dictionary. enumerate() over a dictionary counts its keys, just as a for loop over it gives the keys. For keys and values together, enumerate .items(), from Dictionaries, and unpack each pair:
stock = {"tea": 3, "jam": 0}
for i, key in enumerate(stock):
print(i, key)
for i, (item, qty) in enumerate(stock.items(), start=1):
print(f"{i}. {item}: {qty}")
# ✅ Expected output:
# 0 tea
# 1 jam
# 1. tea: 3
# 2. jam: 0start changes the label, not the position
start=1 changes the number enumerate() reports, not where it reads. The items still sit at positions 0, 1 and 2, so using the label as a position reads the wrong item and then runs off the end:
fruits = ["fig", "kiwi", "plum"]
for n, fruit in enumerate(fruits, start=1):
print(n, fruits[n])
# ✅ Expected output:
# 1 kiwi
# 2 plum
# ✅ Expected error:
# IndexError: list index out of rangeThe item is already in the loop's second name, so use that:
fruits = ["fig", "kiwi", "plum"]
for n, fruit in enumerate(fruits, start=1):
print(n, fruit)
print(list(enumerate(fruits, 1)))
# ✅ Expected output:
# 1 fig
# 2 kiwi
# 3 plum
# [(1, 'fig'), (2, 'kiwi'), (3, 'plum')]The last line shows that start can also be given without its name, as the second argument.
Changing a list's items needs the index
Assigning to the loop's name changes that name, not the list. To replace the items themselves, write through the index that enumerate() gives you:
prices = [4, 10, 7]
for p in prices:
p = p * 2
print(prices)
for i, p in enumerate(prices):
prices[i] = p * 2
print(prices)
# ✅ Expected output:
# [4, 10, 7]
# [8, 20, 14]Replacing items this way is safe, because the list keeps its length. Removing items while looping over the same list is a different trap, which Loops - For and While showed.
zip() stops at the shorter list, without a word
When the lists differ in length, zip() stops at the end of the shorter one and drops the rest of the longer one. There's no error, and no sign that anything went missing:
names = ["Ada", "Ben", "Cleo"]
scores = [88, 72]
for name, score in zip(names, scores):
print(name, score)
print(len(names), len(list(zip(names, scores))))
# ✅ Expected output:
# Ada 88
# Ben 72
# 3 2That's the catch in the lead's "bug-free": if one list is missing an item, zip() hides it. When the lists are meant to be the same length, say so with strict=True (Python 3.10 and later). The pairs that match are still used, and the loop stops with an error when one list runs out before the other:
names = ["Ada", "Ben", "Cleo"]
scores = [88, 72]
for name, score in zip(names, scores, strict=True):
print(name, score)
# ✅ Expected output:
# Ada 88
# Ben 72
# ✅ Expected error:
# ValueError: zip() argument 2 is shorter than argument 1To go on to the end of the longest list instead and fill the gaps, zip_longest() takes a fillvalue; itertools covers it.
A zip is used up after one pass
zip() and enumerate() don't build a list. They hand out one pair at a time, and once they've handed out the last one, they're empty:
pairs = zip(["Ada", "Ben"], [88, 72])
print(list(pairs))
print(list(pairs))
# ✅ Expected output:
# [('Ada', 88), ('Ben', 72)]
# []A zip doesn't know how many pairs it will make, either, so it has no length:
pairs = zip(["Ada", "Ben"], [88, 72])
print(len(pairs))
# ✅ Expected error:
# TypeError: object of type 'zip' has no len()pairs[0] fails the same way, with a TypeError, because a zip has no positions either. When you need the pairs more than once, or need to count or index them, make a list of them:
pairs = list(zip(["Ada", "Ben"], [88, 72]))
print(len(pairs), pairs[0])
print(pairs)
# ✅ Expected output:
# 2 ('Ada', 88)
# [('Ada', 88), ('Ben', 72)]Printing a zip itself shows something like <zip object at 0x7f…>, which is where it sits in memory, because no pair has been made yet. Iterators: __iter__ & __next__ explains how these one-pass objects work.
Two lists into a dictionary, and back
dict() turns pairs into a dictionary, so dict(zip(keys, values)) builds one from two lists. The usual rules apply: a repeated key keeps its last value, and zip() drops a spare value without a word:
print(dict(zip(["a", "b", "a"], [1, 2, 3])))
print(dict(zip(["name", "age"], ["Ada", 36, "London"])))
# ✅ Expected output:
# {'a': 3, 'b': 2}
# {'name': 'Ada', 'age': 36}Going the other way, zip(*pairs) splits a list of pairs into columns. The star spreads the pairs out as separate arguments, as in *args & **kwargs, and zip() pairs up their first items, then their second items:
pairs = [("Ada", 88), ("Ben", 72), ("Cleo", 95)]
names, scores = zip(*pairs)
print(names)
print(scores)
print(list(names))
# ✅ Expected output:
# ('Ada', 'Ben', 'Cleo')
# (88, 72, 95)
# ['Ada', 'Ben', 'Cleo']The columns come back as tuples, so wrap one in list() if you need to add to it. An empty list of pairs gives zip() nothing, so the two names on the left get nothing and the line stops with a ValueError.
Practice: bib numbers for a race
Fill the three blanks with the values in the hint lines, in order, so that each runner gets a bib number starting at 101, printed with their name and time.
runners = ["Ada", "Ben", "Cleo"]
times = [41, 39, 44]
for bib, (runner, time) in ___(___(runners, times), start=___):
print(bib, runner, time)
# 👉 replace ___ with enumerate
# 👉 replace ___ with zip
# 👉 replace ___ with 101
# ✅ Expected output:
# 101 Ada 41
# 102 Ben 39
# 103 Cleo 44On your own: a numbered receipt
A shop keeps its basket in two lists, items = ["tea", "jam", "bread"] and prices = [3, 4, 2]. Print one numbered line per item, starting at 1, such as 1. tea: 3, then the total, 9. Make the program stop with an error if the two lists ever differ in length. Then compare with this solution:
items = ["tea", "jam", "bread"]
prices = [3, 4, 2]
total = 0
for n, (item, price) in enumerate(zip(items, prices, strict=True), start=1):
print(f"{n}. {item}: {price}")
total += price
print("Total:", total)
# ✅ Expected output:
# 1. tea: 3
# 2. jam: 4
# 3. bread: 2
# Total: 9strict=True is what makes a missing price an error instead of a shorter receipt. Try deleting the 2 from prices: the first two lines print, then the ValueError.
Practice quiz
What does list(enumerate("hi", start=1)) give?
- [(1, 'h'), (2, 'i')]
- [(0, 'h'), (1, 'i')]
- ['h', 'i']
- [(1, 'i')]
Answer: [(1, 'h'), (2, 'i')]. enumerate works on text too, and start=1 makes the count begin at 1.
How many lines does for x, y in zip([1, 2, 3], "ab"): print(x, y) print?
- 3
- 2
- It stops with an error
- 6
Answer: 2. zip stops at the end of the shorter one, "ab", so the 3 is never used.
p = zip([1, 2], [3, 4]), then list(p) twice. What does the second list(p) give?
- [(1, 3), (2, 4)]
- None
- []
- An error
Answer: []. A zip hands out each pair once. The first list() used them all.
What does dict(zip("ab", [1, 2, 3])) give?
- {'a': 1, 'b': 2, None: 3}
- An error
- {'ab': [1, 2, 3]}
- {'a': 1, 'b': 2}
Answer: {'a': 1, 'b': 2}. zip makes two pairs and drops the 3 without a word.
nums = [1, 2, 3], then for n in nums: n = n * 10, then print(nums). What prints?
- [10, 20, 30]
- [1, 2, 3]
- [1, 2, 30]
- An error
Answer: [1, 2, 3]. Assigning to n changes the name n, not the list. Use nums[i] with enumerate to change the items.
What does list(enumerate(["a", "b"], 5)) give?
- [(5, 'a'), (6, 'b')]
- [(0, 'a'), (1, 'b')]
- An error
- [(5, 'a'), (5, 'b')]
Answer: [(5, 'a'), (6, 'b')]. The second argument is start, so the count begins at 5.
What does for k, v in enumerate({"x": 1, "y": 2}): print(k, v) print?
- x 1, then y 2
- 0 1, then 1 2
- 0 x, then 1 y
- An error
Answer: 0 x, then 1 y. enumerate over a dictionary counts its keys. Use .items() for the values.
What does for i, a, b in enumerate(zip([1], [2])): print(i, a, b) do?
- It prints 0 1 2
- It prints (0, (1, 2))
- It prints 0 (1, 2)
- It stops with ValueError: not enough values to unpack (expected 3, got 2)
Answer: It stops with ValueError: not enough values to unpack (expected 3, got 2). Each round gets two things, a count and a pair. Write for i, (a, b) in ... to unpack the pair too.
Continue this course
- Previous: Comprehensions
- Next: Checkpoint: Python Essentials — Review & combine the core concepts in a build challenge — then a quiz
- Quick reference: Python cheat sheet › Loops & Iteration
Frequently asked questions
How do I loop backwards with the index?
enumerate() can't run backwards, because it makes its pairs one at a time as the loop asks: reversed(enumerate(names)) stops with a TypeError. Make a list of the pairs first. reversed(list(enumerate(names))) gives the last item first, still with its original index.
How do I sort two lists together?
Zip them so that each pair stays together, then sort the pairs. sorted(zip(scores, names), reverse=True) puts the highest score first, with its name beside it, because pairs are compared by their first item. Sorting with sorted() & key covers sorting by any part of a pair.
Can I zip things that aren't lists?
Yes. zip() and enumerate() take anything a for loop can go through: text, tuples, ranges, a dictionary's keys or items, and the lines of a file. zip("ab", range(2)) pairs each letter with a number. Only a set has no fixed order, so zipping one pairs its items unpredictably.