Index
-
Zip: 1. Definition 2. Syntax 3. Parameter Values 4. Return Values
Zip
Definition
The zip()
function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.
If the passed iterators have different lengths, the iterator with the least items decides the length of the new iterator.
Syntax
zip(iterator1, iterator2, iterator3 ...)
Parameter Values
Parameter | Description |
---|---|
iterator1, iterator2, iterator3 … | Iterator objects that will be joined together |
oss: can be built-in iterables (like: list, string, dict), or user-defined iterables
Recommended Reading: [[Python Iterators, iter and next]]
Return Values
The zip()
function returns an iterator of tuples based on the iterable objects.
-
If we do not pass any parameter,
zip()
returns an empty iterator -
If a single iterable is passed,
zip()
returns an iterator of tuples with each tuple having only one element. -
If multiple iterables are passed,
zip()
returns an iterator of tuples with each tuple having elements from all the iterables.Suppose, two iterables are passed to
zip()
; one iterable containing three and other containing five elements. Then, the returned iterator will contain three tuples. It’s because the iterator stops when the shortest iterable is exhausted.
Examples no parameters:
Examples one parameters:
Examples multiple parameters (same length):
Examples multiple parameters (different length):
UnZipping
Output:
[('x', 3), ('y', 4), ('z', 5)]
c = ('x', 'y', 'z')
v = (3, 4, 5)