PREP WITH PROOF
Menu
PYTHON & DATA PROCESSING / PRACTICAL GUIDE

Python zip(strict=True): Unequal Lengths and Partial Processing

Stop silent zip truncation with tested Python examples for strict length checks, lazy errors, consumed iterators, partial writes, zip_longest and duplicate keys.

THE QUICK ANSWER

Use zip(..., strict=True) when paired inputs must have equal lengths. The check happens during iteration, so early stopping can miss a mismatch and earlier side effects remain. For bounded finite input, validate all pairs before starting writes; use zip_longest when missing positions must stay visible.

A successful loop can still produce an incomplete import

An import pairs three product IDs with two prices. The loop completes without an exception, yet one product never reaches the output. If those columns are required to describe the same rows, silently accepting the shorter result hides a broken data contract. If you deliberately requested only complete pairs, the same result can be correct. Decide which contract applies before changing the call.

This guide uses original, executable fixtures to distinguish truncation, mismatch detection, partial processing and padding. It also shows two limits that strict pairing cannot fix: duplicate dictionary keys and equally long inputs in the wrong order. These matter in imports, generated reports and model-evaluation code where a plausible output can still attach values to the wrong records.

The examples require Python 3.10 or newer for the strict keyword. They were executed with Python 3.12.14. Save the six code blocks together, in displayed order, as zip_contract_demo.py and run python zip_contract_demo.py. They use only the standard library and assertions; success is silent. These are local behavior checks, not throughput or memory benchmarks.

Choose whether a shorter input is acceptable

For the two finite lists below, ordinary zip returns two pairs and leaves the third ID without a price. Enabling strict rejects unequal lengths when the iterator reaches that boundary. The accepted pairs before the boundary are identical; strict is a length-consistency policy rather than a conversion, sorting or value-validation policy.

The first fixture deliberately expects truncation in one assertion and an error in the other. That distinction makes the intended contract visible in a test. Do not change a legitimate complete-pairs workflow into an error merely to add a keyword everywhere. For a required one-to-one row relationship, however, missing data should not disappear silently.

Required behaviorChoiceWhat to verify separately
Use only complete positional pairszip(left, right)Intentional loss of unmatched tail
Require equal finite lengthszip(left, right, strict=True)Complete consumption and row identity
Keep unmatched positions visiblezip_longest with a sentinelMissing-value policy and finite bounds
Match by record identityExplicit key lookup or joinDuplicate IDs, missing keys and ordering
ids = ["p1", "p2", "p3"]
prices = [10, 20]
assert list(zip(ids, prices)) == [("p1", 10), ("p2", 20)]

try:
    list(zip(ids, prices, strict=True))
except ValueError:
    pass
else:
    raise AssertionError("Unequal required columns were accepted")

assert list(zip(["p1", "p2"], [10, 20], strict=True)) == [
    ("p1", 10), ("p2", 20)
]

Source: Python zip: laziness, strict mode and argument order ↗

Creating the iterator does not validate the complete inputs

The second fixture constructs a strict iterator, requests one pair and observes a perfectly valid prefix. The mismatch exists, but that prefix is not proof that the remaining rows fit. A loop that breaks early, a preview function that requests only a few records, or a consumer that stops after finding one match may never reach the inconsistency.

Put exception handling around the operation that actually consumes the pairs. Wrapping only iterator construction misses errors raised later. A successful preview should be described as a preview; do not promote it into a full-file validation result.

The remaining list call below is intentionally the point where validation fails. Fresh input iterators are needed for a fresh attempt: a failed consumer may already have advanced its sources. This guide does not recommend retrying the same exhausted iterator and assuming it represents the original data again.

preview = zip(["p1", "p2"], [10], strict=True)
assert next(preview) == ("p1", 10)

try:
    list(preview)
except ValueError:
    pass
else:
    raise AssertionError("Consuming the remaining input should fail")

Source: PEP 618: length-checking semantics and Python 3.10 introduction ↗

A late mismatch does not roll back earlier work

The third fixture appends each accepted pair to a simulated sink. When the second ID has no corresponding price, the error is caught, but the first append remains. A loop that sends requests, writes rows or updates counters can have the same control-flow problem: detection at the end does not undo previous actions.

For small, finite, bounded inputs, first collect and validate the pairs, then start the downstream operation. The second half of the fixture uses that order and confirms that its sink remains empty on a length mismatch. The list must finish successfully before the loop over staged pairs begins.

This staging boundary prevents these downstream appends from starting on a mismatched input. It does not roll back effects performed by an input generator itself, and it does not make subsequent writes transactional. A write can still fail halfway through the second loop. Use an appropriate transaction or resumable import protocol when downstream operations require stronger guarantees.

Materializing a complete input also requires memory and a terminating source. For an unbounded stream, a remote cursor or a large import, choose a bounded ingestion protocol rather than copying this list pattern blindly. A declared expected count, staged import table and explicit commit phase can provide boundaries that a Python iterator alone cannot supply.

written = []
try:
    for pair in zip(["p1", "p2"], [10], strict=True):
        written.append(pair)
except ValueError:
    pass
assert written == [("p1", 10)]

staged_written = []
try:
    pairs = list(zip(["p1", "p2"], [10], strict=True))
except ValueError:
    pass
else:
    for pair in pairs:
        staged_written.append(pair)
assert staged_written == []

Do not expect unmatched iterator values to remain untouched

The fourth fixture traces successful yields from two generators. Ordinary zip returns one pair, then requests L2 before discovering that the right generator has ended. The second left value has been consumed even though no output tuple contains it. The source cannot be treated as an untouched queue of unmatched records afterward.

The same trace appears for this particular strict mismatch. The fixture checks successful yields rather than counting every next call, so it does not confuse a failed exhaustion probe with a yielded item. Argument order and where exhaustion occurs affect what has been requested; do not generalize this one trace into an exact consumption count for every mismatch shape.

When you need to retain unmatched data, choose an interface that represents it explicitly. Reusing the source iterators after a partial pairing operation is a different contract. The existing iterator-reuse guide linked below explains replay choices; here the key decision is whether unmatched positions belong in the result.

def traced(label, values, events):
    for value in values:
        events.append((label, value))
        yield value

for strict in (False, True):
    events = []
    left = traced("left", ["L1", "L2"], events)
    right = traced("right", ["R1"], events)
    rows = []
    failed = False
    try:
        for row in zip(left, right, strict=strict):
            rows.append(row)
    except ValueError:
        failed = True
    assert rows == [("L1", "R1")]
    assert failed is strict
    assert events == [("left", "L1"), ("right", "R1"), ("left", "L2")]
    assert list(left) == []

Source: PEP 618: length-checking semantics and Python 3.10 introduction ↗

Use a distinct sentinel when a missing value must be visible

The fifth fixture pads the shorter side while preserving a genuine None value on the left. A unique object marks absence. Testing identity with that object distinguishes “no item at this position” from a real data value that happens to be None, zero, an empty string or False.

Padding should expose a missing-data decision, not conceal it behind a plausible replacement. The example records which side is absent and leaves any business action for a later step. For a price import, assigning zero automatically could create a valid-looking but incorrect record; decide whether to reject, quarantine or explicitly mark the row.

The fixture is finite. zip_longest continues with the longer source, so an infinite input needs a deliberate limit. Equal-length detection over a nonterminating source is not a useful end-of-stream check. Define the batch boundary before deciding how to validate it.

from itertools import zip_longest

missing = object()
padded = list(zip_longest([None, "p2"], [10], fillvalue=missing))
assert padded[0] == (None, 10)
assert padded[1][0] == "p2"
assert padded[1][1] is missing

missing_sides = [
    (position, "left" if left is missing else "right")
    for position, (left, right) in enumerate(padded, start=1)
    if left is missing or right is missing
]
assert missing_sides == [(2, "right")]

Source: Python itertools.zip_longest: padding and infinite-input limits ↗

Equal lengths do not guarantee unique keys or correct alignment

The final fixture builds a dictionary from two pairs with the same key. Both columns have equal lengths, so strict pairing succeeds, yet the resulting mapping contains only one key. The later value replaces the earlier one. Length validation and uniqueness validation address separate failures.

The small build_unique_mapping function first consumes the finite inputs into pairs. It then enforces a narrow key policy: nonempty strings with case-sensitive uniqueness. Values are deliberately left unconstrained because their domain belongs to the caller. Duplicate IDs are rejected rather than silently normalized or overwritten.

Even this function cannot infer whether a price belongs to the ID beside it. Equal-length independently sorted lists can be consistently wrong. If each input already carries IDs, align by those IDs and check the join cardinality instead of removing the IDs and hoping positions correspond. Test missing and duplicate identities on both sides.

The helper is intended for small finite inputs that the caller has bounded. It does not implement a general stream validator or protect against a generator that never terminates. Its purpose is to make two checks explicit before returning a mapping; it neither authenticates IDs nor validates price units.

assert dict(zip(["p1", "p1"], [10, 20], strict=True)) == {"p1": 20}

def build_unique_mapping(keys, values):
    pairs = list(zip(keys, values, strict=True))
    result = {}
    for key, value in pairs:
        if not isinstance(key, str) or not key:
            raise ValueError("Keys must be nonempty strings")
        if key in result:
            raise ValueError(f"Duplicate key: {key}")
        result[key] = value
    return result

assert build_unique_mapping(iter(["p1", "p2"]), iter([10, 20])) == {
    "p1": 10, "p2": 20
}
for keys, values in [(["p1", "p1"], [10, 20]), (["p1", "p2"], [10])]:
    try:
        build_unique_mapping(keys, values)
    except ValueError:
        pass
    else:
        raise AssertionError("Invalid mapping input was accepted")

Source: Python dictionaries: construction and duplicate-key replacement ↗

Locate the first broken contract rather than suppressing the error

When strict pairing raises ValueError, inspect how the two inputs were produced. A filter may remove an ID but leave its value, a parser may skip a malformed row in only one column, or a preview may already have consumed one source. Record positions or IDs at the point where the streams diverge; catching the exception and continuing with the prefix hides that evidence.

For stable finite sequences, comparing lengths can give an early diagnostic, but it does not prove item alignment. Generators may have no length at all. Avoid converting an iterator to a list for logging and then handing the consumed iterator to the real import. Capture diagnostic information as part of a deliberate ingestion step.

Keep exception handling narrow. A producer can raise its own ValueError while generating a value, so a broad handler cannot automatically label every such exception as a zip length mismatch. Preserve the traceback and add input context at a boundary where the source and operation are known. Do not parse interpreter-specific error wording as the only validation protocol.

Make the output contract testable before adding side effects

Choose truncation, equality or padding explicitly. Test an empty pair of inputs, unequal lengths in both directions, multiple inputs, a mismatch after several valid pairs, genuine None values and duplicate IDs. Include an early-stop consumer if the application previews or short-circuits; that consumer has not validated the tail.

For a small import, fully stage the bounded pairs, validate the values and identities, and only then start the write phase. For a large workflow, use a batch protocol with observable validation and commit states. In both cases, a length check is one part of correctness, and the test should state exactly which downstream work is allowed to happen before validation finishes.

KEEP THESE THREE THINGS

Your next steps

  1. State whether unmatched positions are rejected, truncated or represented with a sentinel.
  2. Consume the complete bounded input before claiming full length validation; strict pairing does not roll back previous actions.
  3. Validate identity, duplicate keys and value rules separately from the length contract.

Sources & official resources

Linked resources checked on 2026-11-06. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →