The basic shape
for name, score in zip(names, scores):
Each pass gives you the next item from each list. The alternative is for i in range(len(names)) followed by two lookups. That works but puts an index between you and the values.
zip accepts any number of iterables:
for name, score, grade in zip(names, scores, grades):
The function pairs up items by position. The first item from each iterable goes together, then the second, and so on. When the shortest iterable runs out, zip stops. That means if one list has five items and another has three, you get three pairs. The extra items are silently dropped.
This behavior is a common source of bugs when the lists are supposed to be the same length but are not. Python 3.10 added strict=True to catch that case. With zip(a, b, strict=True), a length mismatch raises a ValueError instead of silently truncating.
The pattern zip replaces shows up everywhere. Whenever you have two or more parallel sequences and need to process them together, zip is the tool. Student names in one list and their scores in another. Column headers in one tuple and column values in another. Dates in one array and temperatures in another. Any time the i-th element of one sequence corresponds to the i-th element of another, zip makes the connection explicit.
zip also works as a quick way to build dictionaries. dict(zip(keys, values)) pairs up two sequences into key-value pairs. That single line replaces a loop that inserts entries one at a time.
Unzipping works by applying zip to a list of tuples with the * operator. zip(*pairs) transposes rows into columns. The same function that combines sequences can take them apart again.
This page covers the basic shape, what happens with unequal lengths, strict=True, building dictionaries with zip, and the transpose trick.
Walking two things at once
The job zip does is small and comes up constantly: you've two or more sequences whose spots match, and you want to work with matching items together. Names and scores, keys and values, inputs and expected outputs, columns and headers.
Without it, the loop goes through indices and reaches back into both lists, which reintroduces just the off-by-one risk that looping over items avoids. With it, each iteration hands you one item from each and the indices disappear.
Stopping at the shortest
zip stops when its shortest input runs out. This is a genuine design choice rather than an oversight, and it cuts both ways.
It's convenient when you on purpose pair a finite list against an infinite gen, because you get just as many pairs as the finite side has. It's dangerous when the two lists were supposed to be the same length and aren't, because the extra items are dropped in silence and the program makes a short, plausible, wrong answer.
Since Python 3.10 you can ask for the check:
zip(a, b, strict=True) # ValueError if the lengths differ
Use it when equal lengths are an assumption rather than a coincidence. If you want the opposite - pad the short one instead of truncating - itertools has zip_longest, which fills with None or a value you choose.
Building a dictionary from two lists
dict(zip(keys, values))
This is the standard way to turn parallel lists into a mapping, and it reads better than any loop version. It appears constantly when handling CSV rows, where the header row supplies the keys and each data row supplies the values.
Unzipping
The same function undoes itself, which surprises people:
pairs = [("ana", 91), ("bo", 78)]
names, scores = zip(*pairs)
The star spreads the list of pairs into separate args, and zip then takes one item from each. This Recombines them by spot. The results are tuples rather than lists. This Matters only if you intend to mutate them.
It is lazy
Like map and filter, zip returns an iterator rather than a list. Printing it shows an object, and consuming it twice gives nothing the second time. In a for loop that is invisible and ideal. The moment you want to keep the result, wrap it in list().
A worked example: comparing two lists
The job zip was made for, with enumerate supplying the spot so the report can say where the difference is:
expected = [1, 2, 3]
actual = [1, 5, 3]
for i, (e, a) in enumerate(zip(expected, actual)):
if e != a:
print(f"row {i}: expected {e}, got {a}")
row 1: expected 2, got 5
The double unpacking in for i, (e, a) in is worth reading slowly. enumerate yields (index, item), and here the item is itself the pair zip made, so the brackets take it apart in the same statement. Written without them you'd get i and a tuple. Would have to index into it on the next line.
This is the shape behind most check code: diffing two versions of a record, checking a result against a fixture, lining up a header row with a data row. Note what it does *not* do. If the lists are different lengths, the extra rows are never checked, and the report is silently incomplete. That is the arg for strict=True in one sentence.
Transposing with a star
Mixing the star and zip turns rows into columns:
matrix = [[1, 2, 3], [4, 5, 6]]
print(list(zip(*matrix)))
[(1, 4), (2, 5), (3, 6)]
*mat passes each row as a separate arg, so zip receives two iterables and takes one item from each in turn. Which is just a transpose. The result is a list of tuples rather than lists, and the rows must be the same length or the short one truncates all, both of which are the plain zip rules applied in an unusual place.
This is the same op as unzipping a list of pairs. This Is why both are written zip(*a thing). A list of pairs *is* a two-column mat, and transposing it gives you the two columns.
Where zip removes an index
The value of zip is easiest to see by looking at what it replaces. The index-based version of walking two lists together has to create a counter, bound it right, and reach back into both lists on each line that uses a value.
Each of those is a place to be wrong. The counter can start at one. The bound can use the wrong list's length. This Is fine until the lists differ. The lookups can be transposed, so that names are read from the scores list. None of these give an error. They give wrong output, which is worse.
zip drops all three at once by handing you the values right. There's no counter to get wrong, no bound to find, and no lookup to transpose, because the names arrive already bound to the right variables. This is the same arg as for item in items over for i in range(len(items)), applied to more than one sequence.
The index is still available when you want it. That is what enumerate around a zip is for. But now it's there because you asked, rather than because iteration needed it.
The other things that produce pairs
zip is one of a few things in Python that yield tuples, and they all pair with the same unpacking syntax. Recognising the family makes a lot of loops read the same way.
enumerate(items) yields (index, item). dict.items() yields (key, value). zip(a, b) yields (a_item, b_item). itertools.pairwise yields back to back shared pairs from one sequence. This Is what you want for checking each item with the next.
All four are consumed the same way: for x, y in thing. The unpacking isn't a feature of any of them. It's the plain tuple unpacking from elsewhere in the track, applied to what the loop happened to give. That is why for k, v in d.items() works, and why losing .items() gives you keys and a confusing error rather than a helpful one.
They also combine. zip(a, b, c) for three sequences, enumerate(zip(a, b)) for a spot alongside a pair, zip(d.keys(), d.values()) for the long way of writing d.items().
Parallel lists, and when zip is patching a design problem
zip is the right tool for sequences that truly match, and it's also what lets a questionable data model keep working. So It's worth knowing which situation you're in.
Two lists are parallel when item *i* of one shows the same thing as item *i* of the other. Nothing in the language enforces that. It's an rule living fully in the programmer's head, and each op has to preserve it: sorting one list without the other breaks it, filtering one breaks it, appending to one and losing the other breaks it, and none of those raise.
The failure is quiet and it compounds. A sort applied to names but not to scores makes output where each name has somebody else's score, and the program reports it confidently. There's no assertion that could have caught it without checking against a source of truth that no longer exists.
When the lists are built together and consumed together in one function, that risk is held and zip is just right. When they're stored on an object, passed between functions or returned from an API, the rule has to live code that no one has written yet, and the better structure is one list of records — tuples, dicts, dataclasses — where the name and the score are in the same object and can't be separated.
The tell is a sort. If you find yourself sorting two lists in step, or writing zip, sorting the pairs, and unzipping them again, the data wanted to be pairs all along.
Deciding what unequal lengths mean
Three actions are available and the choice is about what a mismatch would signify in your program. It's worth deciding on purpose rather than taking the default.
Truncating is right when one side is truly open-ended. Pairing a finite list against an infinite counter, taking as many rows as you've templates, reading until the shorter source is exhausted. Here stopping at the shortest is the whole point, and the default does what you want.
Raising is right when equal lengths are an rule. Two lists built from the same source, a header row and a data row, expected and actual results: if they differ, a thing upstream is broken and each line of output after that point is suspect. strict=True converts a wrong answer into an exception, which is almost always the better outcome.
Padding is right when the missing items have a meaning. Filling absent values with None, zero or a default. So That the shorter list is treated as incomplete rather than as terminating the whole op. itertools.zip_longest does this, and choosing the fill value is choosing what "missing" means in the result.
The default is the truncating one. This Means it's the choice you make by not choosing. On any of it where a mismatch would be a bug, that is the wrong default, and one keyword arg fixes it.
Comparing each item with the next
A close scaled of zipping two lists is zipping one list against itself, offset by one, which pairs each item with its successor.
zip(items, items[1:]) does it right: the second arg starts one spot later, so the first pair is items 0 and 1, the second is 1 and 2, and the whole thing stops one short of the end because the offset list is one shorter. That truncation is the default action doing just the right thing for once.
This is the shape for any question about back to back items: are the values growing, where are the gaps in a sequence of dates, what is the difference between each reading and the last. Written with indices it needs a loop from 1 to len(items) and two lookups per pass. Written this way it's one line and has no index at all.
Since Python 3.10 itertools.pairwise(items) does the same thing without the slice, which matters when the input is a gen and can't be sliced.
Questions people ask about zip()
What does zip return? An iterator of tuples. Wrap it in list() to see it or to keep it.
Can I zip more than two things? Yes, any number. Each pass yields a tuple with one item from each.
What if the lists are different lengths? It stops at the shortest, silently. strict=True raises instead, from Python 3.10.
How do I pad the shorter one? itertools.zip_longest, which fills with None or a value you choose.
Can I zip a dict? Yes, and you get its keys, because that is what iterating a dict gives. Use .items() for pairs.
Why did my second loop over a zip do nothing? Because it's an iterator and the first loop consumed it. Build a list if you need it twice.
Does zip copy the data? No. It holds refs and makes tuples on demand, so it works on gens and infinite sequences.
Is zip the same as a DB join? No, and the difference matters. A join matches rows by a key. zip matches them by spot, and has no idea whether the things it paired belong together.
Can I zip strings? Yes. A string is iterable, so zip("abc", "xyz") pairs the characters.
zip(): recap in one screen
zip walks a few iterables in step and yields one tuple per spot, which drops the index and all that can go wrong with it.- It stops at the shortest input without a word. Use
strict=True when equal lengths are an assumption rather than a coincidence. zip(*pairs) unzips, and zip(*mat) transposes — the same op seen from two angles.dict(zip(keys, values)) is the standard way to build a mapping from two parallel lists.- It's lazy, so it works on gens and can only be walked once.