Skip to content

Python zip(): pair iterables safely with strict= (3.10)

  • What zip() yields, why it is a lazy iterator, and how zip(*rows) “unzips”.
  • Why the default behavior of stopping at the shortest input hides bugs, and how strict=True (Python 3.10) fixes that.
  • How to turn CSV rows into dictionaries with dict(zip(header, row, strict=True)) and report bad rows.
  • The traps: one-shot iterators, items lost from an earlier iterator, and errors that arrive late.
  • When itertools.zip_longest, batched, pairwise or enumerate is the better tool.

zip(*iterables, strict=False) iterates over several iterables in parallel and yields tuples: the i-th tuple holds the i-th item of each input. It is lazy, works with any iterable and stops as soon as the shortest input is exhausted. Since Python 3.10 (PEP 618) you can pass strict=True to raise ValueError when the inputs turn out to have different lengths instead of silently dropping the extra items.

In the OrdersPortal order-import job, a parser produces parallel lists: SKUs in one, quantities in another. Pairing them with indexes is verbose and works only for sequences you can index. Worse, a bug upstream that drops one quantity is either an IndexError (if you loop over the longer list) or silently ignored (if you loop over the shorter one).

Running the samples: every sample on this page is a complete script. Save it as a .py file and run it with Python 3.14 (python3 sample.py). The outputs shown were produced with CPython 3.14.6. Samples that need a newer version than 3.10 say so.

skus = ["KB-101", "MS-220", "HD-330"]
quantities = [2, 1] # one quantity is missing
# Before: an index loop. It fails loudly, but only by accident.
try:
for i in range(len(skus)):
print(skus[i], quantities[i])
except IndexError as exc:
print("IndexError:", exc)
# After: zip pairs items by position...
for sku, qty in zip(skus, quantities):
print(sku, qty)
# ...and with strict=True (Python 3.10+) a length mismatch is an error.
try:
for sku, qty in zip(skus, quantities, strict=True):
print(sku, qty)
except ValueError as exc:
print("ValueError:", exc)

Output:

KB-101 2
MS-220 1
IndexError: list index out of range
KB-101 2
MS-220 1
KB-101 2
MS-220 1
ValueError: zip() argument 2 is shorter than argument 1

Plain zip removed the index bookkeeping but kept the bug hidden: HD-330 just disappeared. strict=True keeps the clean loop and makes the mismatch visible, with a message that names the offending argument.

from itertools import zip_longest
pairs = zip(["KB-101", "MS-220"], [2, 1])
print(pairs) # a lazy iterator, not a list
print(list(pairs))
print(list(pairs)) # exhausted after one pass
print(list(zip("AB"))) # one iterable: 1-tuples
print(list(zip())) # no iterables: empty
print(list(zip("ABC", [1, 2], (True, False, None))))
# Unzip: zip(*rows) turns rows into columns
rows = [("KB-101", 2, 49.0), ("MS-220", 1, 19.5)]
skus, qtys, prices = zip(*rows)
print(skus, qtys, prices)
# Pad instead of truncate
print(list(zip_longest("ABC", [1, 2], fillvalue=0)))
# strict=True raises only when the mismatch is reached
lines = zip(["KB-101", "MS-220", "HD-330"], [2, 1], strict=True)
print(next(lines))
print(next(lines))
try:
next(lines)
except ValueError as exc:
print("ValueError:", exc)

Output (the object address varies):

<zip object at 0x7f6f2baffac0>
[('KB-101', 2), ('MS-220', 1)]
[]
[('A',), ('B',)]
[]
[('A', 1, True), ('B', 2, False)]
('KB-101', 'MS-220') (2, 1) (49.0, 19.5)
[('A', 1), ('B', 2), ('C', 0)]
('KB-101', 2)
('MS-220', 1)
ValueError: zip() argument 2 is shorter than argument 1

The rules, all from the built-in functions reference:

  • Lazy, one pass. zip returns an iterator. Nothing is pulled from the inputs until you iterate, and once exhausted it stays empty. Wrap it in list() if you need to index into the pairs or loop twice.
  • Any number of inputs. One iterable gives 1-tuples; no arguments give an empty iterator.
  • Shortest wins by default. Extra items in longer inputs are ignored. That is right when the inputs are infinite or deliberately uneven (zip(itertools.count(1), lines)), and wrong when they are supposed to match.
  • strict=True checks lazily. zip cannot know lengths in advance (inputs may be generators), so it raises ValueError at the moment one input runs out before the others. Every tuple before that point has already been yielded and processed.
  • Left-to-right evaluation is guaranteed. zip pulls one item from each input in order. That makes the chunking idiom zip(*[iter(s)] * n) work, but it also causes the “lost item” trap below.
  • zip(*rows) transposes. Unpacking rows into zip gives columns, so zip is its own inverse. The columns come back as tuples.

Here is the lost-item trap. When a later input runs out, the item zip already pulled from an earlier iterator is discarded:

# zip pulls from its arguments left to right. When a later argument runs
# out, the item already pulled from an earlier *iterator* is lost.
order_ids = iter(["A-1", "A-2", "A-3", "A-4"])
batch_one = list(zip(order_ids, ["paid", "paid"]))
print(batch_one)
print(list(order_ids)) # A-3 was consumed and dropped
# Put the shorter (or bounded) iterable first to avoid losing items.
order_ids = iter(["A-1", "A-2", "A-3", "A-4"])
batch_one = list(zip(["paid", "paid"], order_ids))
print(batch_one)
print(list(order_ids))

Output:

[('A-1', 'paid'), ('A-2', 'paid')]
['A-4']
[('paid', 'A-1'), ('paid', 'A-2')]
['A-3', 'A-4']

The OrdersPortal nightly export is a CSV file. Some rows arrive with a missing column. The import should keep good rows, report bad ones with their line number, then compute line totals and send order IDs to the shipping API in batches. itertools.batched needs Python 3.12; pairwise needs 3.10.

import csv
import io
from itertools import batched, pairwise
EXPORT = """order_id,sku,qty,unit_price
A-1001,KB-101,2,49.00
A-1002,MS-220,1,19.50
A-1003,HD-330,4
A-1004,KB-101,1,49.00
"""
def read_orders(text: str) -> tuple[list[dict[str, str]], list[str]]:
reader = csv.reader(io.StringIO(text))
header = next(reader)
orders, errors = [], []
for line_no, row in enumerate(reader, start=2):
try:
orders.append(dict(zip(header, row, strict=True)))
except ValueError as exc:
errors.append(f"line {line_no}: {exc}")
return orders, errors
orders, errors = read_orders(EXPORT)
for order in orders:
print(order)
print(errors)
# Parallel columns: compute line totals without index bookkeeping.
qtys = [int(o["qty"]) for o in orders]
prices = [float(o["unit_price"]) for o in orders]
totals = [q * p for q, p in zip(qtys, prices, strict=True)]
print(totals)
# Send order IDs to the shipping API two at a time (Python 3.12+).
ids = [o["order_id"] for o in orders]
for batch in batched(ids, 2):
print("ship batch:", batch)
# Compare consecutive totals (Python 3.10+).
print([round(b - a, 2) for a, b in pairwise(totals)])

Output:

{'order_id': 'A-1001', 'sku': 'KB-101', 'qty': '2', 'unit_price': '49.00'}
{'order_id': 'A-1002', 'sku': 'MS-220', 'qty': '1', 'unit_price': '19.50'}
{'order_id': 'A-1004', 'sku': 'KB-101', 'qty': '1', 'unit_price': '49.00'}
['line 4: zip() argument 2 is shorter than argument 1']
[98.0, 19.5, 49.0]
ship batch: ('A-1001', 'A-1002')
ship batch: ('A-1004',)
[-78.5, 29.5]

Two design points. First, dict(zip(header, row, strict=True)) is stricter than csv.DictReader, which fills missing fields of a short row with restval (default None) and so lets the broken A-1003 row through. Second, because the whole row is built before anything is appended, the late ValueError from strict=True cannot leave a half-built order behind; if the loop body had side effects per pair (writing to a database), you would validate lengths first.

  • Relying on default truncation for data that must line up. Parallel lists from the same source should have equal lengths; pass strict=True so a bug raises instead of dropping rows.
  • Iterating a zip object twice. The second loop sees nothing. Materialize it with list(zip(...)) or call zip again.
  • Expecting strict=True to check before the loop starts. It raises when the shortest input runs out, after earlier pairs were processed. Check len() first when the inputs are sequences and partial work is costly.
  • Losing an item from a shared iterator. In zip(it, short_list) the item pulled from it when short_list runs out is gone. Put the bounded input first, or use itertools.islice.
  • Treating unzipped columns as lists. a, b = zip(*rows) gives tuples, and with an empty rows it raises ValueError: not enough values to unpack.
  • Using zip(seq, seq[1:]) for neighbors on large data. The slice copies the list; itertools.pairwise (3.10) is lazy and works on any iterable.

Use zip whenever two or more iterables describe the same items position by position. Pass strict=True unless you deliberately want truncation, for example when one input is infinite.

Need Use
Pair items that must match one to one zip(a, b, strict=True)
Pair with an infinite or deliberately longer input zip(a, b)
Pad the shorter inputs itertools.zip_longest(a, b, fillvalue=...)
Index plus value enumerate(a) (or enumerate(zip(a, b)))
Overlapping neighbors (s0, s1), (s1, s2) itertools.pairwise(s) (3.10)
Fixed-size chunks of one iterable itertools.batched(s, n) (3.12; strict= in 3.13)
Apply a function to parallel items map(f, a, b, strict=True) (strict= in 3.14)

Don’t use zip to join records by key (an order ID, a customer ID): the inputs must already be in the same order. Build a dictionary and look items up instead.

Feature Python version
zip() returning a lazy iterator 3.0
zip(..., strict=True) 3.10 (PEP 618)
itertools.pairwise 3.10
itertools.batched 3.12; strict= added in 3.13
map(..., strict=True) 3.14

All of these are available on Python 3.14, the current release. strict= is a keyword-only argument, so code that passes it fails with TypeError on 3.9 and earlier.

1. What does list(zip([1, 2, 3], "ab")) return, and how would you make the mismatch an error? [(1, 'a'), (2, 'b')]; the 3 is dropped silently. zip([1, 2, 3], "ab", strict=True) raises ValueError: zip() argument 2 is shorter than argument 1 when the second input runs out.

2. How do you transpose a list of rows into columns? cols = list(zip(*rows)). The * passes each row as a separate argument, so zip pairs up the first items, the second items and so on. The result is a list of tuples, and an empty rows gives an empty list.

3. Why can zip(it, other) lose an element from it? zip pulls from its inputs left to right. When other is exhausted, zip has already taken the next item from it and throws it away. Place the shorter input first or slice the iterator explicitly.

4. Senior scenario: an import job zips three parallel columns from a vendor feed and writes each tuple to the database. A vendor bug once shipped a short column, and half a batch was written before anything failed. How do you redesign it? Make the mismatch impossible to miss and impossible to half-apply. Validate up front: if the columns are sequences, compare lengths before writing; if they are streams, zip with strict=True into an in-memory batch (or a staging table) and commit only after the batch is complete, inside a transaction. Better still, ask for row-oriented input so a record cannot be split across columns, and log the row number and offending column on failure so the vendor can fix the source.

  • zip() yields tuples of corresponding items from each input, lazily and only once.
  • By default it stops at the shortest input; since Python 3.10, strict=True raises ValueError on a mismatch.
  • The error arrives when the mismatch is reached, not before; design side effects around that.
  • zip(*rows) transposes rows into columns.
  • Use zip_longest, pairwise, batched, enumerate or a dictionary when they describe the job better.