Skip to content

zip()

zip(*iterables) pairs up elements from two or more iterables position by position, yielding tuples, and stops at the shortest input β€” it never pads or errors for mismatched lengths by default.

names = ["Alice", "Bob"]
ages = [30, 25, 40] # note: 3 items, one more than names
pairs = []
for i in range(min(len(names), len(ages))):
pairs.append((names[i], ages[i]))
names = ["Alice", "Bob"]
ages = [30, 25, 40]
pairs = list(zip(names, ages))
print(pairs) # [('Alice', 30), ('Bob', 25)] -- the extra 40 is silently dropped
for name, age in zip(names, ages):
print(f"{name} is {age}")
# Unzipping β€” the inverse operation
pairs = [('Alice', 30), ('Bob', 25)]
names, ages = zip(*pairs)
print(names, ages) # ('Alice', 'Bob') (30, 25)
  • No manual index bookkeeping: pairing two lists is a one-liner instead of an indexed loop.
  • Works with any number of iterables: zip(a, b, c) pairs three (or more) sequences at once, not just two.
  • Lazy: zip returns an iterator, computing pairs on demand rather than building the whole list upfront β€” matters for large or infinite iterables.
  • zip silently truncates to the shortest iterable β€” a length mismatch is not an error, which can hide bugs. Use itertools.zip_longest(*iterables, fillvalue=None) if you need to pad instead of truncate.
  • zip(*pairs) β€” unpacking a list of tuples back into separate sequences β€” is a common and slightly non-obvious trick (zip is its own inverse when combined with *).
  • In Python 2, zip() returned a list; in Python 3 it returns an iterator, so wrap it in list(...) if you need to index into the result or iterate it more than once.
  1. What does list(zip([1,2,3], ['a','b'])) return?

    Answer`[(1, 'a'), (2, 'b')]` β€” it stops at the shorter iterable (length 2), silently dropping the `3`.
  2. How do you zip together three lists instead of two?

    Answer`zip(list1, list2, list3)` β€” `zip` accepts any number of iterables.
  3. What would you use instead of zip if you wanted mismatched-length inputs padded rather than truncated?

    Answer`itertools.zip_longest(*iterables, fillvalue=...)`.