Reject Mismatched Python Iterables with zip strict

A game content export contains one list of asset IDs and a separate list of download paths. An exporter bug omits the last path. An importer using ordinary zip() appears to succeed, but the last asset never reaches the manifest.

Use zip(strict=True) when each input position must have a partner. This Python 3.10 or later recipe focuses on finite, small batches and on detecting missing positions before calling an external writer.

Reproduce Silent Truncation

Run this small example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
asset_ids = ["hero", "enemy", "background"]
paths = ["hero.png", "enemy.png"]

print(list(zip(asset_ids, paths)))
# [('hero', 'hero.png'), ('enemy', 'enemy.png')]

try:
    list(zip(asset_ids, paths, strict=True))
except ValueError:
    print("Asset IDs and paths have different lengths.")
# Asset IDs and paths have different lengths.

The default call returns two pairs, silently discarding the unmatched tail. Strict mode turns the violated equal-length assumption into an exception. It accepts generators as well as lists, so it does not require both inputs to support len().

The built-in zip documentation describes both behaviors. Strict mode checks how many items arrive; it does not verify that a path belongs to the asset ID beside it. Two equally long lists can still be misaligned.

Understand When the Error Happens

Constructing a strict zip object does not inspect every item. The mismatch appears only as iteration reaches the unequal ending. A loop can already have processed valid pairs by then:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
applied = []
try:
    for asset_id, path in zip(
        ["hero", "enemy"], ["hero.png"], strict=True
    ):
        applied.append((asset_id, path))
except ValueError:
    print("Mismatch detected")

print(applied)
# Mismatch detected
# [('hero', 'hero.png')]

Replacing applied.append() with a database write would leave an update already applied when the exception arrives. Strict iteration supplies detection, without rollback. Breaking out of the loop early also leaves the unvisited suffix unchecked.

PEP 618 introduced this option in Python 3.10. Its specified failure point is the unequal exhaustion boundary. Treat the inputs as consumed after an attempted pass: fetching items and detecting a mismatch can advance their iterators, including an unmatched item. Reusing the same iterators is not a reliable retry strategy.

Prepare the Whole Batch Before Writing

For a small batch, collect all pairs first. Save this as asset_pairs.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def prepare_asset_pairs(asset_ids, paths):
    """Consume finite parallel inputs and validate before returning a batch."""
    pairs = list(zip(asset_ids, paths, strict=True))
    seen = set()
    for asset_id, path in pairs:
        if not isinstance(asset_id, str) or not asset_id:
            raise ValueError("asset ID must be a nonempty string")
        if not isinstance(path, str) or not path:
            raise ValueError("path must be a nonempty string")
        if asset_id in seen:
            raise ValueError("duplicate asset ID")
        seen.add(asset_id)
    return pairs


def apply_asset_pairs(asset_ids, paths, write_pair):
    pairs = prepare_asset_pairs(asset_ids, paths)
    for asset_id, path in pairs:
        write_pair(asset_id, path)

The writer receives no calls until collection and validation finish. A length mismatch, input-iterator exception, empty string, or duplicate ID prevents every writer call. IDs are exact, case-sensitive strings; the helper does not trim them. Paths are opaque nonempty strings here, with no filesystem or URL validation.

Collect tuples before converting to a dictionary. Otherwise repeated IDs could overwrite earlier entries before the application notices the export error. Both empty inputs represent an empty batch; one empty input and one nonempty input are an error.

The helper’s boundary is deliberately limited: a failure inside write_pair can still leave earlier writes applied. Use a database transaction or a separate staged publication step if the writes themselves must commit together.

Test Both Mismatch Directions and Late Failures

Save this beside the module as test_asset_pairs.py and run python -m unittest -v test_asset_pairs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import unittest

from asset_pairs import apply_asset_pairs, prepare_asset_pairs


class AssetPairTests(unittest.TestCase):
    def test_equal_generators_and_empty_inputs(self):
        pairs = prepare_asset_pairs(
            (value for value in ["hero", "enemy"]),
            (value for value in ["hero.png", "enemy.png"]),
        )
        self.assertEqual(pairs, [
            ("hero", "hero.png"), ("enemy", "enemy.png"),
        ])
        self.assertEqual(prepare_asset_pairs([], []), [])

    def test_mismatches_never_call_writer(self):
        for ids, paths in [
            (["hero", "enemy"], ["hero.png"]),
            (["hero"], ["hero.png", "enemy.png"]),
            ([], ["hero.png"]), (["hero"], []),
        ]:
            with self.subTest(ids=ids, paths=paths):
                calls = []
                with self.assertRaises(ValueError):
                    apply_asset_pairs(
                        iter(ids), iter(paths),
                        lambda *pair: calls.append(pair),
                    )
                self.assertEqual(calls, [])

    def test_late_invalid_values_never_call_writer(self):
        for ids, paths in [
            (["hero", "hero"], ["a.png", "b.png"]),
            (["hero", ""], ["a.png", "b.png"]),
            (["hero", "enemy"], ["a.png", None]),
        ]:
            calls = []
            with self.assertRaises(ValueError):
                apply_asset_pairs(ids, paths,
                                  lambda *pair: calls.append(pair))
            self.assertEqual(calls, [])

    def test_input_failure_never_calls_writer(self):
        def failing_paths():
            yield "hero.png"
            raise RuntimeError("export read failed")

        calls = []
        with self.assertRaises(RuntimeError):
            apply_asset_pairs(["hero", "enemy"], failing_paths(),
                              lambda *pair: calls.append(pair))
        self.assertEqual(calls, [])

    def test_success_preserves_pair_order(self):
        calls = []
        apply_asset_pairs(["enemy", "hero"], ["b.png", "a.png"],
                          lambda *pair: calls.append(pair))
        self.assertEqual(calls, [("enemy", "b.png"), ("hero", "a.png")])


if __name__ == "__main__":
    unittest.main()

Test the exception type instead of matching the interpreter’s exact diagnostic text. Both mismatch directions matter, and the late invalid-value cases ensure that one acceptable first pair does not trigger a premature write.

Choose the Appropriate Batch Boundary

This approach holds the complete paired batch in memory. It suits small manifests and bounded configuration exports. Infinite inputs cannot be fully validated this way, and very large imports need a different staging design.

For a large import, stage records in a temporary store, finish reading and validating, then publish through the store’s transaction or commit mechanism. Direct streaming writes require a deliberate partial-progress or rollback policy.

When unequal lengths are intentional, choose the policy explicitly: ordinary zip() keeps only the shared prefix, while itertools.zip_longest() retains extra positions with a fill value. For parallel asset fields that must match, strict iteration plus a completed preparation step makes missing positions visible before external updates begin.