zip(*iterables, strict=False)
Returns an iterator of tuples, where each tuple contains elements from the specified sequences at the same position.
Parameters
iterables: Iterable objects whose elements are packed into tuples. If a single sequence is passed, an iterator of tuples with a single element is returned. If no sequences are passed, an empty iterator is returned. The iterator stops when the shortest sequence is exhausted.
Return Value
The zip() function returns an iterator of tuples based on the iterable objects.
- If no parameters are passed,
zip()returns an empty iterator. - If one iterable is passed,
zip()returns an iterator of tuples, each containing one element. - If multiple iterables are passed,
zip()returns an iterator of tuples, each containing elements from all iterables. For example, if two iterables are passed tozip(), one with three elements and the other with five, the returned iterator contains three tuples. This is because the iterator stops when the shortest iterable is exhausted.
Examples
list(zip([1, 2, 4], [4, 5], [5, 7]))
# [(1, 4, 5), (2, 5, 7)]
Evaluation occurs from left to right, allowing the following idiom for grouping data into n-length clusters: zip(*[iter(s)] * n).
seq = [1, 2, 3, 4, 5, 6]
list(zip(*[iter(seq)] * 2)) # [(1, 2), (3, 4), (5, 6)]
list(zip(*[iter(seq)] * 3)) # [(1, 2, 3), (4, 5, 6)]
With the * operator, the function can unpack a list:
first, second = zip(*[(1, 4), (2, 5), (3, 6)])
# (1, 2, 3), (4, 5, 6)