The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and returns it.
Example
Syntax of zip()
The syntax of the zip() function is:
zip(*iterables)
zip() Parameters
| Parameter | Description |
|---|---|
iterables |
can be built-in iterables (like: list, string, dict), or user-defined iterables |
Recommended Reading: Python Iterators, __iter__ and __next__
zip() Return Value
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 tozip(); 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.
Example 1: Python zip()
Output
[]
{(2, 'two'), (3, 'three'), (1, 'one')}
Example 2: Different number of iterable elements
Output
{(2, 'TWO'), (3, 'THREE'), (1, 'ONE')}
{(2, 'two', 'TWO'), (1, 'one', 'ONE')}
The * operator can be used in conjunction with zip() to unzip the list.
zip(*zippedList)
Example 3: Unzipping the Value Using zip()
Output
[('x', 3), ('y', 4), ('z', 5)]
c = ('x', 'y', 'z')
v = (3, 4, 5)