zip()
What it is
Section titled βWhat it isβ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.
Before this feature
Section titled βBefore this featureβ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]))After this feature
Section titled βAfter this featureβ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 operationpairs = [('Alice', 30), ('Bob', 25)]names, ages = zip(*pairs)print(names, ages) # ('Alice', 'Bob') (30, 25)Why this is better
Section titled βWhy this is betterβ- 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:
zipreturns an iterator, computing pairs on demand rather than building the whole list upfront β matters for large or infinite iterables.
Key notes / edge cases
Section titled βKey notes / edge casesβzipsilently truncates to the shortest iterable β a length mismatch is not an error, which can hide bugs. Useitertools.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 (zipis its own inverse when combined with*).- In Python 2,
zip()returned a list; in Python 3 it returns an iterator, so wrap it inlist(...)if you need to index into the result or iterate it more than once.
Quick practice
Section titled βQuick practiceβ-
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`. -
How do you zip together three lists instead of two?
Answer
`zip(list1, list2, list3)` β `zip` accepts any number of iterables. -
What would you use instead of
zipif you wanted mismatched-length inputs padded rather than truncated?Answer
`itertools.zip_longest(*iterables, fillvalue=...)`.