Sub topic 7
When lengths differ: truncation, strict=True, and zip_longest
This chapter assumes you can write a for loop over a list, unpack tuples in a loop header, and use zip to loop over two sequences in parallel. Here you will see what zip does when its inputs have different lengths, and how to choose a different behavior on purpose.
The default: zip stops at the shortest input
zip pairs items by position. When one input runs out, zip stops. It does not raise an error, and it does not warn you. The extra items in the longer inputs are never used.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88]
for name, score in zip(names, scores):
print(f"{name}: {score}")This prints two lines, for Ada and Grace. Linus is dropped because scores has no third item.
This behavior is called truncation. It is convenient when you want it, for example when you pair a long list with a short one on purpose. It is a quiet source of bugs when the lengths should have matched and one list lost data earlier in your program.
Choosing a behavior
You have three options. Pick the one that matches what the mismatch means in your program.
| Situation | Tool | Result for unequal lengths |
|---|---|---|
| Extra items are not needed | `zip(a, b)` | Stops at the shortest input |
| Lengths must match, and a mismatch is a bug | `zip(a, b, strict=True)` | Raises `ValueError` |
| You need every item from the longest input | `itertools.zip_longest(a, b)` | Pads the shorter input with a fill value |
Failing loudly with strict=True
Since Python 3.10, zip accepts a strict argument. With strict=True, zip raises ValueError as soon as it finds that the inputs have different lengths.
a = [1, 2, 3]
b = ["x", "y"]
try:
list(zip(a, b, strict=True))
except ValueError:
print("lengths differ")Use this when two lists are meant to be parallel, such as column names and column values. A length mismatch then points to a bug somewhere else, and you want to hear about it immediately.
The check happens during iteration, not before it. If you loop with for, the pairs that match are produced first, and the error is raised when zip reaches the point where one input is exhausted and another is not.
a = [1, 2, 3]
b = ["x", "y"]
try:
for number, letter in zip(a, b, strict=True):
print(number, letter)
except ValueError as error:
print("error:", error)The loop prints 1 x and 2 y before the error appears. If your loop body has side effects, such as writing to a file, those side effects have already happened for the matching pairs. When that matters, compare lengths with len() before the loop, or collect the result with list(...) inside a try block.
Keeping every item with zip_longest
Sometimes you need all the data, and a missing value is acceptable. itertools.zip_longest runs until the longest input is finished. It fills the gaps in shorter inputs with None by default, or with the value you give in fillvalue.
from itertools import zip_longest
a = [1, 2, 3]
b = ["x", "y"]
print(list(zip(a, b)))
# [(1, 'x'), (2, 'y')]
print(list(zip_longest(a, b, fillvalue="-")))
# [(1, 'x'), (2, 'y'), (3, '-')]Note that zip_longest lives in the itertools module, so you must import it. The fill value applies to every input. You cannot give one fill value to a and a different one to b.
Common errors
- Assuming
zipchecks lengths. It does not, unless you passstrict=True. - Passing
strict=Trueand expecting an error before any iteration. The error comes when the mismatch is reached. - Using
zip_longestwithout afillvalueand then calling a method onNone. - Forgetting the import:
zip_longestis not a built-in name. - Counting on
zipto tell you which input was longer. If you need that, comparelen()values yourself first.
Exercise
You load ids = [101, 102, 103, 104] and emails = ["[email protected]", "[email protected]", "[email protected]"]. Each id should have exactly one email. Write a loop that prints each pair and raises an error if the lists do not match in length. Then say what a loop using zip_longest(ids, emails, fillvalue="missing") would print for the last pair.
Show answer
Use for user_id, email in zip(ids, emails, strict=True): print(user_id, email). The loop prints 101, 102 and 103 with their emails, then raises ValueError because emails ran out while ids still had 104. With zip_longest(ids, emails, fillvalue="missing"), the last pair would be (104, 'missing'), so the loop prints 104 missing.
Exercise
Why can zip(a, b) hide a bug that zip(a, b, strict=True) would catch?
Show answer
Plain zip stops at the shortest input without any error, so items left in the longer input are silently skipped. With strict=True, a length mismatch raises ValueError, so the problem shows up instead of producing incomplete results.