zip()
Iterate over several sequences in parallel, pairing up their items by position.
zip(*iterables, strict=False)
Purpose
zip(*iterables) walks two or more iterables together, producing tuples that pair up the item at
each shared position — the standard way to loop over parallel data (names and their scores,
labels and values) without indexing into each list separately.
Example
names = ["apples", "bananas", "cherries"]
quantities = [12, 3, 40]
for name, qty in zip(names, quantities):
print(f"{name}: {qty}")
apples: 12
bananas: 3
cherries: 40
Behavior notes
zipstops as soon as its shortest input iterable is exhausted — ifnameshad four items andquantitieshad three, the fourth name is silently dropped, with no error.- Since Python 3.10, passing
strict=Truemakeszipraise aValueErrorinstead of silently truncating when the iterables have different lengths — worth reaching for whenever mismatched lengths would actually be a bug rather than something expected. zipis lazy, likeenumerate— it produces tuples one at a time rather than building a list of them up front. Wrap it inlist(...)to see all the pairs at once.zip(*pairs)(with a single already-zipped argument, unpacked) reverses azip— a common, if slightly dense-looking, idiom for “transposing” paired data back into separate sequences.
Common mistakes
- Assuming a length mismatch between the inputs raises an error by default — it doesn’t; the
extra items in the longer iterable are silently discarded unless
strict=Trueis passed. - Indexing into two lists in a loop (
for i in range(len(names)): names[i], quantities[i]) instead of zipping them — it works, but it’s more code and more opportunities for an off-by-one mistake.
Implementation notes
zip’s pairing and shortest-wins truncation are language guarantees. strict=True is a real,
version-gated addition — unavailable before Python 3.10.