Zip Function in Python
zip() function is used to group multiple iterators. It is used to map similar indexes of multiple containers.
How Python's zip() Function Works
Let's start by looking up the documentation for zip() and parse it in the subsequent sections.
Syntax: zip(*iterators)
Parameters: Python iterables or containers ( list, string, etc )
Return Value: Returns a single iterator object, having mapped values from all the containers.
Make an iterator that aggregates elements from each of the iterables.
1. Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.
2. The iterator stops when the shortest input iterable is exhausted.
3. With a single iterable argument, it returns an iterator of 1-tuples.
4. With no arguments, it returns an empty iterator. – Python Docs
How the zip() Function Creates an Iterator of Tuples
The following illustration helps us understand how the zip() function works by creating an iterator of tuples from two input lists, L1 and L2. The result of calling zip() on the iterables is displayed on the right.
- Notice how the first tuple (at index 0) on the right contains 2 items, at index 0 in L1 and L2, respectively.
- The second tuple (at index 1) contains the items at index 1 in L1 and L2.
- In general, the tuple at index i contains items at index i in L1 and L2.
Example
## initializing two lists |
If you run the above program, you will get the following results.
('Harry', 'Emma', 'John') (19, 20, 18) |
General Usage Of zip()
We can use it to print the multiple corresponding elements from different iterators at once. Let's look at the following example.
Example 1
## initializing two lists |
If you run the above program, you will get the following result
Output
Harry's age is 19 |
Example 2 : Python zip enumerate
names = ['Mohan', 'Rohan', 'Yash'] |
Output
0 Mohan 34 |
Example 3 : Python zip() dictionary
stocks = ['realme', 'ibm', 'apple'] |
Output
{'realme': 2175, 'ibm': 1127, 'apple': 2750} |