zip(strict=True) Catches Uneven Iterables
Make uneven inputs loud with zip(strict=True): what plain zip silently truncates becomes an explicit ValueError, even when a streamed side runs dry.
Code
# 普通 zip 静默截断到最短输入——少一行数据没有任何报错
names = ["alpha", "beta", "gamma"]
prices = [9.5, 4.0, 12.25, 0.0]
print("plain zip stops at:", [p for _, p in zip(names, prices)])
# strict=True 把 uneven 输入变成显式 ValueError
try:
list(zip(names, prices, strict=True))
except ValueError as err:
print("strict caught:", err)
# 等长输入照常两两配对:订单号与 SKU 一一对应
print("paired:", list(zip(iter([1001, 1002, 1003]), iter(["X1", "X2", "X3"]), strict=True)))
# 流式搬数据时一侧断供(多出一行),同样被 strict 抓住
try:
list(zip(iter([1001, 1002, 1003, 1004]), iter(["X1", "X2", "X3"]), strict=True))
except ValueError as err:
print("stream caught:", err)Output
Captured from a sandboxed run of this snippet in the build pipeline.
plain zip stops at: [9.5, 4.0, 12.25]
strict caught: zip() argument 2 is longer than argument 1
paired: [(1001, 'X1'), (1002, 'X2'), (1003, 'X3')]
stream caught: zip() argument 2 is shorter than argument 1What to watch for
The first half shows the failure mode plain zip hides: names holds 3 entries and prices holds 4, yet zip(names, prices) yields only three pairs and never mentions the dropped 0.0 — the list comprehension prints [9.5, 4.0, 12.25] and moves on.
Adding strict=True turns that silence into a ValueError. The first try block catches zip() argument 2 is longer than argument 1, naming which side overran. Equal-length inputs are unaffected: the paired line zips two length-3 iterators with strict=True and gets the full [(1001, 'X1'), (1002, 'X2'), (1003, 'X3')] result.
The last block covers the streaming case, where lengths are not known up front: one side produces an extra item mid-iteration, and strict zip still raises — this time zip() argument 2 is shorter than argument 1. Both error strings are in the captured output, so uneven inputs surface as loud failures instead of lost rows.
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library.
Report a problem with this exampleOpens a pre-filled issue on GitHub.