Sub topic 7
When lengths differ: truncation, strict=True, and zip_longest
This chapter assumes you can write for loops over lists, unpack tuples in a loop header, and use zip on two sequences of equal length. It also assumes you know that zip returns an iterator. You will learn what happens when the inputs to zip have different lengths, and three ways to handle it.
The default: zip stops at the shortest input
zip produces one tuple per position. When any input runs out, zip stops. It does not raise an error, and it does not warn you.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88]
for name, score in zip(names, scores):
print(f"{name}: {score}")The output is:
Ada: 95
Grace: 88Linus never appears. If scores was supposed to have three entries, you have lost a row of data and nothing told you.
This behavior is called truncation. It is useful when you want it and hazardous when you don't.
When truncation is what you want
Some loops rely on truncation. A common one pairs each item with its successor:
readings = [10, 14, 21, 25]
for current, following in zip(readings, readings[1:]):
print(f"change: {following - current}")The second argument is one item shorter than the first, so the loop makes three pairs and stops. No special handling for the last element is needed.
Truncation also lets you pair a finite sequence with an endless counter:
from itertools import count
tasks = ["write", "test", "ship"]
for number, task in zip(count(1), tasks):
print(f"{number}. {task}")count(1) never ends, but tasks does, so the loop ends too. This is the same result as enumerate(tasks, start=1), and enumerate is the clearer choice for that job. The example shows why zip must stop at the shortest input: otherwise it could not be used with infinite iterators at all.
When truncation is a bug
Truncation is a bug when the inputs are supposed to line up. Typical cases are parallel lists from two files, columns of a table, or a list of IDs and a list of results from an API. If one list comes back short, the loop quietly processes fewer items than you expected.
Your three options are:
- Accept truncation, because it is correct for this loop.
- Fail loudly with
strict=True. - Keep every item and fill the gaps with
itertools.zip_longest.
A subtle effect: which input loses an item
When zip stops, it may already have taken an item from one of the inputs and thrown it away. This matters when you keep using an iterator after the loop.
zip asks its inputs for the next item in the order you listed them. When the first input is longer, zip takes an item from it, then asks the second input, which is empty. The item from the first input is gone.
it = iter([1, 2, 3])
short = [10, 20]
print(list(zip(it, short)))
# [(1, 10), (2, 20)]
print(list(it))
# []The value 3 was removed from it and discarded when zip found that short was empty. Now swap the order:
it = iter([1, 2, 3])
short = [10, 20]
print(list(zip(short, it)))
# [(10, 1), (20, 2)]
print(list(it))
# [3]Here short runs out first, so zip never asks it for a third item, and 3 is still there.
This only affects iterators you continue to use afterward, such as an open file or a generator. If you pass lists, nothing is lost, because a list is not consumed by iteration. If you need to keep the remainder, put the shorter or finite input first, or use zip_longest and handle the gap yourself.
strict=True: make a mismatch an error
Python 3.10 added a keyword argument to zip. With strict=True, zip raises ValueError if the inputs have different lengths.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88]
try:
for name, score in zip(names, scores, strict=True):
print(f"{name}: {score}")
except ValueError as exc:
print("error:", exc)The output is:
Ada: 95
Grace: 88
error: zip() argument 2 is shorter than argument 1The message names the first argument that doesn't match, by position. If the first input is the shorter one, the message says argument 2 is longer than argument 1.
How strict checking works
strict=True does not check lengths up front. Many iterables, such as generators and file objects, have no length. Instead, zip detects the mismatch during iteration, when one input is exhausted and another still has items. This has two consequences.
First, the matching pairs are produced before the error. In the example above, the loop body ran for Ada and Grace, and only then did ValueError appear. If the loop body has side effects, such as writing to a database or sending a message, some work is already done when the error is raised. If you need all-or-nothing behavior, check first or collect the results into a list inside a try block and use them only after the loop succeeds.
Second, the error appears at the end of iteration. If you stop the loop early with break, the mismatch might never be detected.
a = [1, 2, 3]
b = ["x", "y"]
for number, letter in zip(a, b, strict=True):
print(number, letter)
break
# prints: 1 x (no error, because the loop stopped before the mismatch)strict works with iterators, len checks do not
A pre-check with len() is the usual alternative:
if len(names) != len(scores):
raise ValueError("names and scores must have the same length")This works for lists and tuples, but fails with a TypeError for generators and other iterators without a length. strict=True works for every kind of input, and it is shorter. Use it on Python 3.10 or later.
Compatibility
On Python versions before 3.10, passing strict raises TypeError because zip does not accept keyword arguments. If your project supports older versions, use the len() check, or convert the inputs to lists first.
zip_longest: keep everything and fill the gaps
If you want a pair for every item of the longest input, use itertools.zip_longest. It runs until all inputs are exhausted and substitutes a fill value for the ones that ran out.
from itertools import zip_longest
names = ["Ada", "Grace", "Linus"]
scores = [95, 88]
for name, score in zip_longest(names, scores, fillvalue=0):
print(f"{name}: {score}")The output is:
Ada: 95
Grace: 88
Linus: 0The fillvalue argument sets the padding. If you leave it out, the default is None:
from itertools import zip_longest
print(list(zip_longest([1, 2, 3], ["x"])))
# [(1, 'x'), (2, None), (3, None)]Note that fillvalue must be passed by keyword. There is only one fill value, and it applies to every input. You cannot give one input a different filler than another.
The None collision
None is a poor default when None is also a legitimate value in your data. After padding, you cannot tell a real None from a filler.
Use a private sentinel object instead. A sentinel is a unique object that cannot appear in your data:
from itertools import zip_longest
_MISSING = object()
left = [1, None, 3]
right = ["a", "b"]
for x, y in zip_longest(left, right, fillvalue=_MISSING):
if y is _MISSING:
print(f"{x!r}: no match on the right")
else:
print(f"{x!r} -> {y!r}")The output is:
1 -> 'a'
None -> 'b'
3: no match on the rightThe None in left pairs normally with "b", and only the real gap is flagged. Compare with is, because the sentinel is identified by identity, not by value.
Padding a ragged table
zip_longest combines well with the zip(*rows) transpose from a later chapter. Rows of unequal length can be turned into columns, with gaps filled:
from itertools import zip_longest
rows = [[1, 2, 3], [4, 5], [6]]
columns = list(zip_longest(*rows, fillvalue=0))
print(columns)
# [(1, 4, 6), (2, 5, 0), (3, 0, 0)]Plain zip(*rows) would produce only one column here, (1, 4, 6), because the shortest row has one item.
Never use zip_longest with an infinite iterator
zip ends when its shortest input ends, so an endless input is safe as long as one input is finite. zip_longest ends only when the longest input ends. With an endless input, it never ends.
from itertools import count, islice, zip_longest
# zip_longest(count(), "ab") would loop forever.
# Bound the endless input explicitly if you need this:
print(list(zip_longest(islice(count(), 4), "ab", fillvalue="-")))
# [(0, 'a'), (1, 'b'), (2, '-'), (3, '-')]Wrap the endless input in islice to set a limit first.
Choosing between the three
| Situation | Choice | Why |
|---|---|---|
| Inputs are meant to differ in length, such as pairing items with their successors | `zip` | Truncation is the point. |
| Inputs must match, and a mismatch means a bug upstream | `zip(..., strict=True)` | The bug becomes an exception instead of lost data. |
| Every item of the longest input must be kept | `zip_longest` | Missing values are filled instead of dropped. |
| You must support Python before 3.10 | `zip` plus a `len()` check | `strict` is not available. |
| One input is infinite | `zip` | `zip_longest` never ends, and `strict` would raise as soon as the finite input ends. |
Combining with enumerate
All three variants return an iterator of tuples, so they work inside enumerate with the nested unpacking from the previous chapter:
names = ["Ada", "Grace", "Linus"]
scores = [95, 88]
try:
for i, (name, score) in enumerate(zip(names, scores, strict=True), start=1):
print(i, name, score)
except ValueError as exc:
print("error:", exc)The output is:
1 Ada 95
2 Grace 88
error: zip() argument 2 is shorter than argument 1The strict check belongs on zip, not on enumerate. enumerate takes one input and creates its own counter, so it has no length mismatch to detect.
Edge cases
A few boundary cases behave in ways that surprise people:
- An empty input.
zip([], [1, 2, 3])produces nothing. Withstrict=Trueit raisesValueError, because one input is empty and the other is not. Two empty inputs pass the strict check and simply produce no pairs. - A single input.
zip([1, 2, 3])yields one-item tuples:(1,),(2,),(3,). There is no length to compare, sostricthas no effect. - No inputs.
zip()is valid and produces nothing. - More than two inputs. Truncation stops at the shortest of all of them.
strict=Trueraises if any input differs from the first.zip_longestpads each input independently with the same fill value. - Strings count by character.
zip("abc", [1, 2])pairs'a'with1and'b'with2. A string is an iterable of characters, so its length is the number of characters. - Already-consumed iterators. If an input was used up earlier,
zipsees it as empty, and the result is empty or a strict error. Chapter 10 covers this in detail.
Common errors
- Using plain
zipon data that must align. Fix: addstrict=True, or validate lengths first. - Catching
ValueErrortoo broadly. Atryblock around a long loop body will also catchValueErrorraised by your own code. Keep thetrynarrow, or check for the specific message. - Using
zip_longestand forgetting that the filler isNone. Arithmetic on the filler fails withTypeError, such asNone + 1. Setfillvalueto a number, or handle the gap explicitly. - Treating a
stricterror as a data-cleaning step. The exception tells you the data is wrong. It does not tell you which items are missing. If you need to find them, usezip_longestwith a sentinel to locate the gaps. - Assuming
zip_longestaccepts per-input fill values. It accepts exactly onefillvalue.
Summary
zipstops at the shortest input without any signal. It may consume one extra item from earlier inputs before it stops.zip(..., strict=True)raisesValueErrorwhen lengths differ. The error is raised during iteration, after the matching pairs have been produced.itertools.zip_longestcontinues to the longest input and fills gaps withfillvalue, which defaults toNone. Use a sentinel object whenNoneis valid data.- Use plain
zipwhen truncation is the design,strict=Truewhen a mismatch is a bug, andzip_longestwhen every item must be kept.
Exercise
You have ids = [101, 102, 103] and emails = ["[email protected]", "[email protected]"]. Write a loop that prints every ID, showing "(none)" for IDs that have no email.
Show answer
Use zip_longest with a fill value on the shorter list, and put the sentinel text there:
from itertools import ziplongest
ids = [101, 102, 103]
emails = ["[email protected]", "[email protected]"]
for userid, email in ziplongest(ids, emails, fillvalue="(none)"):
print(userid, email)
This prints 101 [email protected], 102 [email protected], and 103 (none). Note that this works because ids is the longer list. If emails could be the longer one, the filler "(none)" would also appear in the ID position, so a sentinel check would be safer.
Exercise
What does this code print, and why? it = iter([1, 2, 3]); print(list(zip(["a", "b"], it))); print(list(it))
Show answer
It prints [('a', 1), ('b', 2)] and then [3]. The list ["a", "b"] is listed first, so zip finds it exhausted before it asks the iterator for a third item. The value 3 is still in the iterator. If the arguments were swapped, zip would take 3 from the iterator first and discard it when the list ran out, and the second print would show [].
Exercise
A function receives two generators, left and right, that should produce the same number of items. Why is a len() check not an option here, and what do you use instead? What happens to the items produced before a mismatch is found?
Show answer
Generators have no length, so len() raises TypeError. Use zip(left, right, strict=True) on Python 3.10 or later. The mismatch is detected only during iteration, so the pairs before the mismatch are already produced and processed when ValueError is raised. If the loop body has side effects, collect the pairs into a list inside a try block and act on them only after the list is complete.