Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps
Python zip() takes two or more iterables and pairs their items by position, so you can loop over several lists at once. Learn how to build dictionaries, unzip with *, catch length mismatches with strict=True, keep extra items with zip_longest, and avoid the traps that silently lose data.
- Python zip pairs items by position:
zip(names, scores)gives(name, score)tuples. - It stops at the shortest input without warning; in our test a 3-item and a 2-item list produced only 2 pairs.
strict=True(Python 3.10+) turns that silent loss into aValueError;zip_longestkeeps every item instead.zip(*pairs)unzips and also transposes rows and columns.
Two lists that belong together, such as names and scores, dates and prices or keys and values, are everywhere in real code. Looping over them by index works but reads poorly and breaks easily. Python zip is the built-in that walks them side by side. Every output in this guide comes from code we ran on Python 3.13.6.
Quick answer
names = ["Asha", "Ravi", "Li"]
scores = [91, 78, 85]
for name, score in zip(names, scores):
print(name, score)
Asha 91
Ravi 78
Li 85
Each pass gives one item from each list, matched by position. If you also need the position, combine it with enumerate(): for i, (name, score) in enumerate(zip(names, scores), 1).
How zip() works
zip() accepts any number of iterables: lists, tuples, strings, ranges, files or generators. It returns an iterator of tuples, where the first tuple holds the first item of every input, the second holds the second items, and so on:
print(list(zip(names, scores)))
print(list(zip(range(3), "abc", [True, False, True])))
[('Asha', 91), ('Ravi', 78), ('Li', 85)]
[(0, 'a', True), (1, 'b', False), (2, 'c', True)]
Two edge cases are worth knowing: zip() with no arguments gives an empty result, and zip(names) with one argument gives one-item tuples such as ('Asha',).
Build a dictionary from two lists
print(dict(zip(names, scores)))
{'Asha': 91, 'Ravi': 78, 'Li': 85}
This is the most common real-world use: turning parallel lists, such as CSV headers and a row of values, into a dictionary. The same trick inverts a dictionary: dict(zip(d.values(), d.keys())) turned {"x": 1, "y": 2} into {1: 'x', 2: 'y'} in our run. Duplicate values would collapse into one key, so check first. More dictionary patterns are in our Python dictionary guide.
What happens with uneven lengths
This is the behaviour that causes real bugs. By default, zip stops as soon as the shortest input runs out:
print(list(zip(names, [1, 2])))
[('Asha', 1), ('Ravi', 2)]
“Li” vanished without any error. If those lists came from two API calls or two columns of a file, a missing row would quietly drop data from your report.
strict=True: fail loudly on mismatches
Python 3.10 added a strict flag, described in PEP 618, for exactly this problem:
list(zip(names, [1, 2], strict=True))
ValueError: zip() argument 2 is shorter than argument 1
Tip: use strict=True whenever the lists are supposed to be the same length. A crash during testing is far cheaper than a silently short report in production.
zip_longest: keep every item
When lists may legitimately differ and you want everything, use itertools.zip_longest with a fill value:
from itertools import zip_longest
print(list(zip_longest(names, [1, 2], fillvalue=0)))
[('Asha', 1), ('Ravi', 2), ('Li', 0)]
Without fillvalue the gaps are None. Our Python itertools guide covers its siblings.
| Tool | Uneven inputs | Use when |
|---|---|---|
zip(a, b) |
Stops at shortest, silently | Truncation is intended |
zip(a, b, strict=True) |
Raises ValueError | Lengths must match |
zip_longest(a, b) |
Pads with a fill value | Every item must appear |
Unzip with the * operator
There is no unzip() function, because zip() does both jobs. Unpack a list of pairs with * and zip them again:
pairs = [("Asha", 91), ("Ravi", 78), ("Li", 85)]
names, scores = zip(*pairs)
print(names, scores)
('Asha', 'Ravi', 'Li') (91, 78, 85)
zip(*pairs) passes each pair as a separate argument, so zip collects all first items together and all second items together. Note that the results are tuples; wrap them in list() if you need to modify them.
Transpose rows and columns
m = [[1, 2, 3], [4, 5, 6]]
print([list(r) for r in zip(*m)])
[[1, 4], [2, 5], [3, 6]]
The same unpacking trick turns rows into columns. It is handy for small tables, such as turning CSV rows into per-column lists. For large numeric data, NumPy is far faster.
Compare each item with the next
Zipping a list with itself, shifted by one, gives neighbouring pairs:
data = [3, 5, 9, 14]
print([b - a for a, b in zip(data, data[1:])]) # [2, 4, 5]
from itertools import pairwise
print(list(pairwise(data))) # [(3, 5), (5, 9), (9, 14)]
This calculates day-over-day changes, gaps between timestamps or step sizes. On Python 3.10 and later, itertools.pairwise does the same without copying the list.
Split into fixed-size chunks
print(list(zip(*[iter(range(7))] * 3)))
[(0, 1, 2), (3, 4, 5)]
This classic idiom passes the same iterator three times, so each tuple takes the next three items. But notice the trap: item 6 disappeared because the last chunk was incomplete. Use itertools.batched (Python 3.12+) or zip_longest when every item matters.
zip() is a one-shot iterator
z = zip(names, scores)
print(type(z).__name__, list(z), list(z))
zip [('Asha', 91), ('Ravi', 78), ('Li', 85)] []
The second list(z) was empty because the iterator was already used up. This laziness is why zip works on huge files and generators without extra memory, but it also means you cannot loop over the same zip object twice. Store list(zip(...)) if you need it again.
Is zip faster than indexing?
We looped over two 1,000-item lists 2,000 times, best of five runs:
| Loop style | Time |
|---|---|
for x, y in zip(a, b) |
0.047 s |
for i in range(len(a)): x = a[i]; y = b[i] |
0.065 s |
zip took about 28% less time and reads more clearly. The difference is small in absolute terms, so choose zip for readability; the speed is a bonus.
Three real-world uses
Turn a CSV row into a record
header = "name,dept,salary".split(",")
row = "Asha,QA,90000".split(",")
print(dict(zip(header, row, strict=True)))
{'name': 'Asha', 'dept': 'QA', 'salary': '90000'}
Pairing a header with each row is exactly what csv.DictReader does for you, but the zip version is useful for one-off strings, log lines and API responses that arrive as parallel arrays. Adding strict=True catches a row with a missing or extra column immediately, instead of producing a record with a shifted value. Note that every value is still text; convert numbers yourself.
Find what changed between two versions
old = {"price": 10, "stock": 5, "name": "Pen"}
new = {"price": 12, "stock": 5, "name": "Pen"}
print([(k, a, b) for k, a, b in zip(old, old.values(), new.values()) if a != b])
[('price', 10, 12)]
This works because both dictionaries were built with the same key order. If the order could differ, compare by key instead: [(k, old[k], new[k]) for k in old if old[k] != new.get(k)]. Assuming matching order is a classic zip bug, so be explicit about it.
Check test inputs against expected outputs
inputs = [2, 5, 0]
expected = [4, 25, 0]
print(all(x * x == e for x, e in zip(inputs, expected, strict=True))) # True
Parallel lists of inputs and expected results are common in quick checks and data-driven tests. In a real test suite, prefer one list of pairs, which cannot drift out of step, or pytest parametrize.
zip vs enumerate vs itertools.product
These three are often confused. zip pairs items by position across several sequences. enumerate pairs each item with a counter. itertools.product pairs every item with every other, like nested loops: product("ab", [1, 2]) gave ('a', 1), ('a', 2), ('b', 1), ('b', 2), four results where zip would give two. Choose by the question you are asking: “which items belong together?” is zip, “where is this item?” is enumerate, and “all combinations?” is product.
Common mistakes
- Silent truncation: lists of different lengths lose data. Add
strict=True. - Reusing a zip object: it is empty the second time.
- Zipping sets or unordered data: sets have no guaranteed order, so pairs can be mismatched. Sort first; see our Python sort list guide.
- Expecting lists back from unzip:
zip(*pairs)returns tuples. - Forgetting the incomplete last chunk with the
[iter(x)] * nidiom.
Python zip cheat sheet
| Goal | Code |
|---|---|
| Loop two lists | for a, b in zip(x, y) |
| Lists to dict | dict(zip(keys, values)) |
| Require equal length | zip(x, y, strict=True) |
| Keep all items | zip_longest(x, y, fillvalue=0) |
| Unzip pairs | a, b = zip(*pairs) |
| Transpose | list(zip(*matrix)) |
| Neighbour pairs | zip(x, x[1:]) or pairwise(x) |
| With a counter | enumerate(zip(x, y)) |
Final thoughts
Python zip() is one of the simplest ways to make loops clearer: it pairs related data by position and removes index bookkeeping. Remember its one dangerous default, stopping at the shortest input, and guard against it with strict=True or zip_longest. Add zip(*...) for unzipping and transposing, and you have covered nearly every real use. For building new lists from zipped data, our list comprehension guide is the natural next step.
Frequently asked questions
What does zip() do in Python?
It takes two or more iterables and returns an iterator of tuples, where each tuple holds the items at the same position from every input.
What happens if lists have different lengths in zip?
zip stops at the shortest input and silently drops the extra items. Use strict=True to raise an error instead, or itertools.zip_longest to keep every item with a fill value.
How do you unzip a list of tuples in Python?
Use zip with the unpacking operator: a, b = zip(*pairs). It returns tuples, so wrap them in list() if you need lists.
How do I make a dictionary from two lists?
Call dict(zip(keys, values)). Add strict=True on Python 3.10 or later if the two lists must have the same length.
Why is my zip object empty the second time?
zip returns a one-time iterator. Once you loop over it or call list() on it, it is used up. Save the result as a list if you need it again.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.