Built-in Functions
zip Function
Combining iterables element-by-element for parallel iteration
Interview: Common in interviews — dict creation from two lists, matrix transposition, and parallel processing
zip() combines multiple iterables into a single iterable of tuples, where the i-th tuple contains the i-th element from each input iterable. It's one of the most frequently used built-in functions for parallel iteration, creating dictionaries from two lists, and matrix transposition.
Basic zip Behavior
- Stops at shortest: zip truncates to the length of the shortest iterable — no error for unequal lengths
- Returns iterator: In Python 3, zip returns a lazy iterator (use list() to see all results)
- Multiple iterables: zip can combine any number of iterables — not just two
- Single iterable:
zip([1, 2, 3])yields (1,), (2,), (3,) — tuples of length 1
Unzipping with *
- Transpose:
zip(*zipped)reverses the zip operation — like transposing a matrix - Unpack tuples:
names, ages = zip(*pairs)separates columns from rows
zip_longest
- From itertools:
from itertools import zip_longest - Stops at longest: Fills missing values with fillvalue (default: None)
- Use when: You need all elements from all iterables, even if lengths differ
Python 3.10+ strict mode
Python 3.10 added zip(a, b, strict=True) which raises ValueError if iterables have different lengths. Use this when you expect equal lengths and want to catch data mismatches early.
zip is Lazy
zip() returns an iterator that is consumed after one pass. If you need to iterate multiple times, convert to a list first: pairs = list(zip(a, b)). Also, zip with generators consumes them — be careful with side effects.
Use Cases
Parallel iteration over multiple sequences simultaneously
Creating dictionaries from separate key and value lists
Matrix transposition and column extraction from 2D data
Sliding window patterns for comparing consecutive elements
Grouping flat sequences into chunks of N elements
Common Mistakes
Forgetting that zip truncates to shortest — use zip_longest or strict=True when lengths should match
Not converting zip result to list when you need to iterate multiple times (zip is consumed)
Confusing zip() the function with .zip the file format — they are unrelated
Using zip where dict(zip(keys, values)) is simpler for creating lookup tables
Forgetting the unzip trick: zip(*zipped) reverses a zip operation