Python zip(): pair iterables safely with strict= (3.10)
What you’ll learn
Section titled “What you’ll learn”- What
zip()yields, why it is a lazy iterator, and howzip(*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,pairwiseorenumerateis the better tool.
Summary
Section titled “Summary”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.
The problem it solves
Section titled “The problem it solves”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 2MS-220 1IndexError: list index out of rangeKB-101 2MS-220 1KB-101 2MS-220 1ValueError: zip() argument 2 is shorter than argument 1Plain 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.
How it works
Section titled “How it works”from itertools import zip_longest
pairs = zip(["KB-101", "MS-220"], [2, 1])print(pairs) # a lazy iterator, not a listprint(list(pairs))print(list(pairs)) # exhausted after one pass
print(list(zip("AB"))) # one iterable: 1-tuplesprint(list(zip())) # no iterables: emptyprint(list(zip("ABC", [1, 2], (True, False, None))))
# Unzip: zip(*rows) turns rows into columnsrows = [("KB-101", 2, 49.0), ("MS-220", 1, 19.5)]skus, qtys, prices = zip(*rows)print(skus, qtys, prices)
# Pad instead of truncateprint(list(zip_longest("ABC", [1, 2], fillvalue=0)))
# strict=True raises only when the mismatch is reachedlines = 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 1The rules, all from the built-in functions reference:
- Lazy, one pass.
zipreturns an iterator. Nothing is pulled from the inputs until you iterate, and once exhausted it stays empty. Wrap it inlist()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=Truechecks lazily. zip cannot know lengths in advance (inputs may be generators), so it raisesValueErrorat 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 intozipgives 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']Realistic example
Section titled “Realistic example”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 csvimport iofrom itertools import batched, pairwise
EXPORT = """order_id,sku,qty,unit_priceA-1001,KB-101,2,49.00A-1002,MS-220,1,19.50A-1003,HD-330,4A-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.
Common mistakes
Section titled “Common mistakes”- Relying on default truncation for data that must line up. Parallel lists from the same source should have equal lengths; pass
strict=Trueso a bug raises instead of dropping rows. - Iterating a zip object twice. The second loop sees nothing. Materialize it with
list(zip(...))or callzipagain. - Expecting
strict=Trueto check before the loop starts. It raises when the shortest input runs out, after earlier pairs were processed. Checklen()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 fromitwhenshort_listruns out is gone. Put the bounded input first, or useitertools.islice. - Treating unzipped columns as lists.
a, b = zip(*rows)gives tuples, and with an emptyrowsit raisesValueError: 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.
When to use it and when not to
Section titled “When to use it and when not to”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.
Compatibility
Section titled “Compatibility”| 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.
Interview questions
Section titled “Interview questions”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.
Key takeaways
Section titled “Key takeaways”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=TrueraisesValueErroron 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,enumerateor a dictionary when they describe the job better.
Related pages
Section titled “Related pages”- Python enumerate(): index and value together, often combined with
zip. - Python itertools:
zip_longest,pairwise,batchedand other iterator tools. - Splat operator: the
*unpacking behindzip(*rows). - List comprehensions: build lists from zipped pairs.
- Python iterators and generators: why a zip object is exhausted after one pass.
- Python loops: the
forloop patterns zip replaces.