How to Use zip() with strict=True in Python

In Python 3.10 and later, the built-in zip() function includes a strict=True keyword argument designed to prevent silent bugs caused by mismatched iterable lengths. This article explains how the strict=True parameter changes the default behavior of zip(), how it handles multiple inputs of differing sizes, and the specific exceptions it raises to keep your code safe and predictable.

Default zip() Behavior vs. strict=True

By default, Python's zip() function stops iterating as soon as the shortest input iterable is exhausted. Any remaining elements in longer iterables are silently ignored:

names = ["Alice", "Bob", "Charlie"]
scores = [85, 92]

# Default behavior: stops after 2 elements, silently drops "Charlie"
result = list(zip(names, scores))
print(result)
# Output: [('Alice', 85), ('Bob', 92)]

While convenient in some contexts, this silent truncation frequently masks bugs when the datasets are assumed to align one-to-one. Setting strict=True forces zip() to verify that all inputs have the exact same length.

How strict=True Handles Iterables

When strict=True is enabled, zip() pairs elements from each iterable in lockstep. If all iterables contain the same number of items, zip() yields tuples normally without error:

names = ["Alice", "Bob"]
scores = [85, 92]

result = list(zip(names, scores, strict=True))
print(result)
# Output: [('Alice', 85), ('Bob', 92)]

However, if one iterable is shorter or longer than the others, Python raises a ValueError the moment it detects a mismatch:

names = ["Alice", "Bob", "Charlie"]
scores = [85, 92]

try:
    list(zip(names, scores, strict=True))
except ValueError as e:
    print(e)
    # Output: zip() argument 2 is shorter than argument 1

Behavior with Three or More Iterables

When passing three or more iterables, zip(..., strict=True) compares lengths dynamically as it advances. It raises a ValueError as soon as any iterable terminates while at least one other still has remaining values:

ids = [1, 2, 3]
names = ["Alice", "Bob"]
scores = [85, 92, 78]

try:
    list(zip(ids, names, scores, strict=True))
except ValueError as e:
    print(e)
    # Output: zip() argument 2 is shorter than argument 1

Because zip() evaluates inputs lazily, elements produced prior to the length mismatch are yielded normally before the exception is raised.

Summary

The strict=True keyword argument guarantees that all input iterables to zip() are equal in length. If any iterable runs out before the others, a descriptive ValueError is raised immediately, eliminating silent data loss and making data pipelines more robust.