Beginner   Chapter 144 · 25 min read · Module 11: Advanced Python

Zip

Learning objectives
  • After this chapter you can explain what zip does and what it returns.
  • You can loop over two or more lists at the same time.
  • You can build dictionaries and lists of tuples with zip.
  • You can handle lists of different lengths with zip, strict=True and itertools.zip_longest.
  • You can unzip data with the star operator.

Real data often lives in separate lists that belong together. You may have one list of names and another list of marks, where the first name goes with the first mark. To work with them you need a way to walk through both lists side by side.

The built-in zip function does exactly this. It takes two or more iterables and produces tuples, where each tuple holds one item from every iterable. The name comes from a zipper, which joins two sides tooth by tooth.

In this chapter you will learn how zip works, what happens when the lists have different lengths, and how to use it to make dictionaries, compare lists and flip rows into columns.

Looping over two lists together

Imagine a list of students and a list of their marks. If you write a loop over range(len(names)) and read names[i] and marks[i], the code works but is noisy. With zip(names, marks) you get one pair per step, and you can unpack the pair directly in the for statement. The pairs are built from items in the same position, so the first name meets the first mark, the second meets the second, and so on.

Example 1: Pairing names and marks
names = ["Asha", "Ben", "Chen"]
marks = [82, 74, 91]
for name, mark in zip(names, marks):
    print(name, mark)
Asha 82 Ben 74 Chen 91
zip: a built-in function that combines items from several iterables, position by position, into tuples

Like enumerate and map, zip returns a lazy iterator, not a list. It produces each tuple only when the loop asks for it. If you want to see all the tuples at once, wrap the result in list(). An iterator can be read only once, so after you have used it up it will be empty.

Example 2: Zip makes tuples
a = [1, 2, 3]
b = ["x", "y", "z"]
z = zip(a, b)
print(list(z))
print(list(z))
print(list(zip(a, b, [True, False, True])))
[(1, 'x'), (2, 'y'), (3, 'z')] [] [(1, 'x', True), (2, 'y', False), (3, 'z', True)]

The second print shows an empty list because the first list(z) consumed the iterator. The third line shows that zip can take any number of iterables, and each tuple then has that many items.

Different lengths

When the iterables have different lengths, zip stops as soon as the shortest one runs out. The extra items in the longer lists are silently ignored. This can hide bugs, because you may lose data without any error message. Since Python 3.10 you can add strict=True, which raises a ValueError if the lengths differ. If you want to keep every item, use itertools.zip_longest, which fills the gaps with a value you choose.

Example 3: Shortest wins, strict and zip_longest
from itertools import zip_longest

short = [1, 2]
long = ["a", "b", "c", "d"]
print(list(zip(short, long)))
print(list(zip_longest(short, long, fillvalue=0)))
try:
    list(zip(short, long, strict=True))
except ValueError:
    print("lengths differ")
[(1, 'a'), (2, 'b')] [(1, 'a'), (2, 'b'), (0, 'c'), (0, 'd')] lengths differ
The strict option needs Python 3.10 or newer. Use it when the lists are meant to be the same length, so that a mismatch is caught early.

Making dictionaries and comparing lists

A very popular use of zip is to build a dictionary from a list of keys and a list of values. You write dict(zip(keys, values)). Zip is also useful to compare two sequences item by item, for example to count how many positions are equal, or to compute pairwise sums and differences.

Example 4: Dictionary and pairwise sums
keys = ["id", "name", "city"]
values = [7, "Ria", "Pune"]
record = dict(zip(keys, values))
print(record)

x = [1, 2, 3]
y = [10, 20, 30]
print([p + q for p, q in zip(x, y)])
print(sum(1 for p, q in zip("hello", "help!") if p == q))
{'id': 7, 'name': 'Ria', 'city': 'Pune'} [11, 22, 33] 3

Unzipping with the star operator

Zip is almost its own opposite. If you have a list of pairs, you can split them back into separate groups by writing zip(*pairs). The star operator unpacks the list into separate arguments, so zip sees each pair as its own iterable and regroups the first items together, the second items together, and so on. The same trick turns the rows of a table into columns, which is called transposing.

Example 5: Unzip and transpose
pairs = [(1, "a"), (2, "b"), (3, "c")]
numbers, letters = zip(*pairs)
print(numbers)
print(letters)

grid = [[1, 2, 3], [4, 5, 6]]
print([list(col) for col in zip(*grid)])
(1, 2, 3) ('a', 'b', 'c') [[1, 4], [2, 5], [3, 6]]

Notice that unzipping gives tuples, not lists. If you need lists, convert them with list(). You can also combine zip with enumerate, for example for i, (a, b) in enumerate(zip(x, y)), which gives a counter plus both values in each step. The extra round brackets in the loop header match the nested tuple.

Zip in everyday code

Zip is handy whenever data is stored by column. A spreadsheet export, for example, often gives one list for each column, and zip lets you rebuild the rows. It is also a neat way to look at neighbouring items in a single list: zip(items, items[1:]) gives each item paired with the one after it. This is helpful to find differences between consecutive readings or to check that a list is sorted.

Example 6: Neighbouring items
temps = [20, 23, 22, 25]
print([b - a for a, b in zip(temps, temps[1:])])
print(all(a <= b for a, b in zip(temps, temps[1:])))
[3, -1, 3] False

Python syntax

Syntax
for a, b in zip(list1, list2):
    ...
Syntax
pairs = list(zip(a, b, c))
Syntax
mapping = dict(zip(keys, values))
Syntax
zip(a, b, strict=True)   # Python 3.10+
Syntax
a_part, b_part = zip(*pairs)

Real-world applications

  • Combining related lists such as names and scores.
  • Building dictionaries from separate key and value lists.
  • Transposing rows and columns of a table.
  • Comparing two sequences position by position.
  • Looking at neighbouring values to find changes.

Common mistakes

Mistake: Expecting zip to return a list and printing it directly.
Fix: Use list(zip(...)) when you want to see or reuse the pairs.
Mistake: Not noticing that zip stops at the shortest iterable.
Fix: Check the lengths, use strict=True on Python 3.10+, or use zip_longest.
Mistake: Reusing a zip object after it has been consumed.
Fix: Create a new zip, or store the pairs in a list first.
Mistake: Forgetting the star when unzipping, as in zip(pairs).
Fix: Write zip(*pairs) so each pair becomes a separate argument.
Mistake: Unpacking into the wrong number of names.
Fix: The number of names must equal the number of iterables passed to zip.

Important tips

  • Use meaningful names in the loop such as for name, mark in zip(names, marks).
  • Prefer strict=True when the lists must match.
  • Wrap in list() while debugging.
  • Combine zip with enumerate when you also need a counter.

Key points summary

  • zip pairs items by position.
  • It stops at the shortest iterable.
  • It returns a one-use iterator.
  • dict(zip(keys, values)) makes a dictionary.
  • zip(*data) unzips or transposes.
  • strict=True (3.10+) raises an error for unequal lengths.

Exam and interview points

  • zip returns an iterator, not a list.
  • The output length equals the shortest input.
  • strict=True was added in Python 3.10.
  • zip(*zip(a, b)) gives back the original data as tuples.

Quick revision

  • zip(a, b) gives (a0, b0), (a1, b1), ...
  • Shortest iterable decides the length.
  • dict(zip(k, v)) builds a dictionary.
  • zip(*rows) transposes.
  • list(zip(...)) to display.

Frequently asked questions

What does zip return?

It returns a zip object, which is an iterator of tuples. Convert it with list() or loop over it.

What happens if the lists have different lengths?

zip stops when the shortest one ends and ignores the rest. Use strict=True to raise an error or zip_longest to keep every item.

Can I zip more than two lists?

Yes. zip accepts any number of iterables and each tuple has one item from each.

How do I unzip a list of pairs?

Use the star operator: first, second = zip(*pairs). The results are tuples.

Is zip the same as enumerate?

No. enumerate pairs items with a counter, while zip pairs items from several iterables with each other.

Practise this chapter

20 practice questions Take the chapter quiz

Related chapters