iteration
zip()
Pairs elements from multiple iterables into tuples, stopping at the shortest. With strict=True, raises ValueError if lengths differ.
zip(*iterables, strict=False) Parameters
| Parameter | Purpose |
|---|---|
| *iterables | Two or more iterables to combine |
| strict | Require equal-length inputs (Python 3.10+) |
Examples
list(zip([1, 2], ['a', 'b'])) Returns [(1, 'a'), (2, 'b')]
list(zip([1, 2, 3], ['a', 'b'])) Returns [(1, 'a'), (2, 'b')] — extra dropped
dict(zip(['x', 'y'], [1, 2])) Returns {'x': 1, 'y': 2}
list(zip(*[[1, 2], [3, 4]])) Returns [(1, 3), (2, 4)] — matrix transpose
Gotcha
Silent truncation on unequal lengths is a common bug — use strict=True (Python 3.10+) when lengths must match.
Related built-ins
enumerate()
Yields (index, item) tuples from an iterable. Preferred over manual index counters in for-loops.
map()
Applies a function to each item of one or more iterables, yielding results lazily. Returns a map object (iterator), not a list.
filter()
Yields items from iterable for which function(item) is truthy. If function is None, filters out falsy items.
range()
Returns an immutable range object representing an arithmetic sequence of integers. Memory-efficient — values are computed lazily, not stored.