Sub topic 8
Using enumerate and zip Together
Earlier chapters introduced enumerate for index-and-value loops and zip for parallel loops. This chapter combines them. You will see the standard pattern, the unpacking rules behind it, the alternative nesting orders, and what happens with unequal lengths and one-shot iterators.
This chapter assumes you know:
- How
enumerate(seq, start=n)andzip(a, b)work on their own. - How tuple unpacking works in a
forheader. - That both functions return lazy, one-shot iterators.
Why combine them
Sometimes you walk several parallel sequences and also need the position of each step. Typical cases are:
- Numbered output, such as a ranked leaderboard.
- Error messages that say which row went wrong.
- Comparing two lists and reporting the index of each difference.
Without these tools, you would write one of two awkward versions:
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
# Awkward: manual indexing into both lists
for i in range(len(names)):
print(i + 1, names[i], scores[i])
# Awkward: a separate counter
rank = 1
for name, score in zip(names, scores):
print(rank, name, score)
rank += 1The first version breaks if the lists differ in length. The second spreads the counter over three places: initialization, use, and increment. Combining the two functions removes both problems.
The standard pattern
Wrap zip in enumerate, then unpack the result with nested parentheses.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
for rank, (name, score) in enumerate(zip(names, scores), start=1):
print(f"{rank}. {name:<6} {score}")Output:
1. Ada 95
2. Grace 88
3. Linus 91The for header uses rank, (name, score). To see why, look at what each function yields.
zip(names, scores)yields two-item tuples:("Ada", 95), then("Grace", 88), and so on.enumerate(...)takes that stream and yields(index, item)pairs. Eachitemis itself a tuple, so you get(1, ("Ada", 95)).- The header pattern
rank, (name, score)mirrors that shape. The outer level has two parts, and the second part is a tuple that is unpacked again.
The nesting is not decoration. The parentheses in the header must match the nesting of the data.
The most common error: flat unpacking
A frequent mistake is to write the header flat, as if the three values arrived side by side:
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
try:
for i, name, score in enumerate(zip(names, scores)):
print(i, name, score)
except ValueError as error:
print("ValueError:", error)Output:
ValueError: not enough values to unpack (expected 3, got 2)enumerate always yields exactly two things: the counter and one item. The item happens to be a tuple, but Python does not look inside it unless the header asks for that with parentheses. The message "expected 3, got 2" tells you the header has more targets than the outer tuple has parts.
The reverse mistake, adding parentheses where the data is flat, gives "cannot unpack non-iterable int object" or a similar message. When unpacking fails, print one item from the iterator and compare its shape to your header:
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
print(next(enumerate(zip(names, scores))))
# (0, ('Ada', 95))Three or more sequences
zip accepts any number of inputs, and the same rule applies: the inner parentheses grow to match.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
grades = ["A", "B", "A"]
for i, (name, score, grade) in enumerate(zip(names, scores, grades), start=1):
print(f"{i}: {name} scored {score} ({grade})")Output:
1: Ada scored 95 (A)
2: Grace scored 88 (B)
3: Linus scored 91 (A)The outer level stays at two parts however many sequences you zip. Only the inner tuple changes size.
Alternative nesting orders
enumerate(zip(a, b)) is the usual form, but other arrangements produce different shapes. Pick the one that reads best for your loop.
| Expression | Shape of each item | Header |
|---|---|---|
| `enumerate(zip(a, b))` | `(i, (x, y))` | `for i, (x, y) in` |
| `zip(enumerate(a), b)` | `((i, x), y)` | `for (i, x), y in` |
| `zip(range(n), a, b)` | `(i, x, y)` | `for i, x, y in` |
| `zip(count(1), a, b)` | `(i, x, y)` | `for i, x, y in` |
The second form is useful when one sequence is the "main" one and the other is a side input. Both forms give the same result:
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
for (i, name), score in zip(enumerate(names), scores):
print(i, name, score)The flat forms use range or itertools.count as the counter inside zip. They avoid nested parentheses, but they have two weaknesses:
- With
range(n), you must computenyourself and keep it in sync with the data. If you get it wrong, the loop silently stops early. itertools.count(1)is infinite, which is safe with plainzipbecause it stops at the shortest input. It is not safe in combination withstrict=True, as the next section shows.
For most code, enumerate(zip(...)) is the clearest choice. It needs no length and no import.
Unequal lengths
All the length rules from the zip chapter still apply. enumerate just adds a counter on top, and it numbers only the items that zip actually produces.
Default truncation
a = [1, 2, 3]
b = ["x", "y"]
for i, (number, letter) in enumerate(zip(a, b)):
print(i, number, letter)Output:
0 1 x
1 2 yThe loop stops after two pairs, and the 3 is never seen. No error is raised.
Detecting mismatches with strict=True
On Python 3.10 and later, strict=True turns a length mismatch into an error:
a = [1, 2, 3]
b = ["x", "y"]
try:
for i, (number, letter) in enumerate(zip(a, b, strict=True), start=1):
print(i, number, letter)
except ValueError as error:
print("error:", error)Output:
1 1 x
2 2 y
error: zip() argument 2 is shorter than argument 1The error appears only when zip tries to fetch the item after the last complete pair. The loop body has already run for the matching items. If the body has side effects, such as writing rows or sending messages, check the lengths first when you need all-or-nothing behavior:
a = [1, 2, 3]
b = ["x", "y"]
if len(a) != len(b):
raise ValueError(f"length mismatch: {len(a)} vs {len(b)}")That check only works for sized sequences. For generators and files you cannot call len, so strict=True is the practical option.
Do not combine strict=True with a counter inside zip
zip(count(1), a, strict=True) or zip(range(10), a, strict=True) fails whenever the counter's length differs from the data. This is the main reason to prefer enumerate for counting. It is never a separate zip argument, so it cannot cause a mismatch.
Padding with zip_longest
To keep the extra items, use itertools.zip_longest:
from itertools import zip_longest
a = [1, 2, 3]
b = ["x", "y"]
for i, (number, letter) in enumerate(zip_longest(a, b, fillvalue="-")):
print(i, number, letter)Output:
0 1 x
1 2 y
2 3 -The shape of each item is unchanged, so the header stays the same. Only the number of iterations differs.
Counting how many items were processed
After a for loop, the loop variable keeps its last value. This gives a tempting way to count:
a = [1, 2, 3]
b = ["x", "y"]
for i, (number, letter) in enumerate(zip(a, b)):
pass
print(i + 1) # 2This breaks when the inputs are empty. The loop body never runs, i is never assigned, and the last line raises NameError. A safer idiom pre-sets the counter and uses start=1:
a = [1, 2, 3]
b = ["x", "y"]
count = 0
for count, (number, letter) in enumerate(zip(a, b), start=1):
print(number, letter)
print("pairs processed:", count)With start=1, count after the loop equals the number of items processed. For empty input it stays at the preset 0.
Worked example: reporting differences
A common real task is comparing two sequences and reporting where they differ.
expected = ["a", "b", "c", "d"]
actual = ["a", "x", "c", "y"]
for i, (want, got) in enumerate(zip(expected, actual)):
if want != got:
print(f"index {i}: expected {want!r}, got {got!r}")Output:
index 1: expected 'b', got 'x'
index 3: expected 'd', got 'y'The same pattern works with files, because a file object is an iterator over its lines. This compares two text sources line by line without loading either into a list. Here StringIO stands in for real files:
from io import StringIO
old = StringIO("a\nb\nc\n")
new = StringIO("a\nB\nc\n")
for number, (before, after) in enumerate(zip(old, new), start=1):
if before != after:
print(f"line {number}: {before.rstrip()!r} -> {after.rstrip()!r}")Output:
line 2: 'b' -> 'B'Here start=1 matches how editors and error messages number lines, so a person can jump straight to the reported line.
Enumerating columns with zip(*rows)
zip(*rows) transposes a table, turning rows into columns. Wrapping it in enumerate gives each column its index:
rows = [
[1, 2, 3],
[4, 5, 6],
]
for col, column in enumerate(zip(*rows)):
print(col, column, sum(column))Output:
0 (1, 4) 5
1 (2, 5) 7
2 (3, 6) 9The result of zip(*rows) yields tuples, so column is a tuple. Here the header needs no inner parentheses because we keep each column whole instead of unpacking it.
Building a dictionary from the combined loop
Because the combined loop gives you an index and the paired values together, a dictionary comprehension can key records by position:
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
by_rank = {
rank: (name, score)
for rank, (name, score) in enumerate(zip(names, scores), start=1)
}
print(by_rank)Output:
{1: ('Ada', 95), 2: ('Grace', 88), 3: ('Linus', 91)}Pitfalls
The combined iterator is also one-shot
enumerate(zip(...)) is an iterator wrapped around an iterator, so it can be consumed only once. It also has no length:
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
pairs = enumerate(zip(names, scores), start=1)
print(list(pairs))
# [(1, ('Ada', 95)), (2, ('Grace', 88)), (3, ('Linus', 91))]
print(list(pairs))
# []
try:
len(pairs)
except TypeError as error:
print("TypeError:", error)
# TypeError: object of type 'enumerate' has no len()If you need to loop twice, either build the iterator again for each loop or store the result with list(...). Build it again when the inputs are large and you want to avoid holding everything in memory. Store it when creating the iterator is expensive or the inputs cannot be read twice.
zip can consume an item you never see
When some inputs are iterators rather than lists, the order of arguments matters. zip asks for the next item from each input in argument order. If an earlier input yields a value and a later one is exhausted, that value is already gone.
it = iter([1, 2, 3, 4])
short = ["x", "y"]
print(list(zip(it, short)))
# [(1, 'x'), (2, 'y')]
print(next(it))
# 4 (the 3 was pulled from it and discarded)
it = iter([1, 2, 3, 4])
print(list(zip(short, it)))
# [(‘x’, 1), ('y', 2)]
print(next(it))
# 3Putting the shorter input first leaves the longer iterator untouched. This rarely matters for lists, but it matters when you continue using an iterator after the loop, for instance when reading a file in stages.
Checklist for the combined pattern
- Wrap
zipinsideenumerate, and givestart=1for numbers shown to people. - Make the header's parentheses match the data:
i, (a, b, c). - Add
strict=Truewhen equal lengths are a requirement, not an assumption. - Use
zip_longestwhen the extra items matter. - Convert to a list if you need to loop more than once or call
len.
Exercise
This loop raises ValueError: not enough values to unpack (expected 3, got 2). Fix the header and say why the error occurs.
for i, name, city in enumerate(zip(names, cities), start=1): print(i, name, city)
Show answer
Change the header to for i, (name, city) in enumerate(zip(names, cities), start=1):. enumerate yields exactly two parts, the counter and one item. The item is the (name, city) tuple from zip, so it must be unpacked with its own parentheses. The flat header asked for three parts from a two-part tuple.
Exercise
Given a = ["x", "y", "z"] and b = [10, 20], what does list(enumerate(zip(a, b), start=1)) return? What happens if you add strict=True to the zip call and loop over the result? Which lines of the loop body run?
Show answer
The first expression returns [(1, ('x', 10)), (2, ('y', 20))], because zip truncates to the shorter input and enumerate numbers only the pairs it receives. With strict=True, the loop body runs for the first two pairs. The ValueError ("zip() argument 2 is shorter than argument 1") is raised when zip tries to produce a third pair, after the second iteration has finished. Passing the result to list(...) would raise the error before returning anything.
Exercise
Write a loop that takes two lists, old and new, and prints row N: old_value -> new_value for each position where the values differ. Number rows from 1. Raise an error if the lists have different lengths.
Show answer
for row, (before, after) in enumerate(zip(old, new, strict=True), start=1): followed by if before != after: print(f"row {row}: {before} -> {after}"). The strict=True argument raises ValueError when the lengths differ, and start=1 numbers rows from 1. The error is raised after matching rows have been compared. If you need to reject mismatched input before any output, compare len(old) and len(new) first.