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
names = ['Harry', 'Emma', 'John']
ages = [19, 20, 18]
## zipping both
## zip() will return pairs of tuples with corresponding elements from both lists
zipped = list(zip(names, ages))
## unzipping
new_names, new_ages = zip(*zipped)
## checking new names and ages
print(new_names)
print(new_ages)

If you run the above program, you will get the following results.

('Harry', 'Emma', 'John')

(19, 20, 18)

write your code here: Coding Playground

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
names = ['Harry', 'Emma', 'John']
ages = [19, 20, 18]
## printing names and ages correspondingly using zip()
for name, age in zip(names, ages):
print(f"{name}'s age is {age}")

If you run the above program, you will get the following result

Output

Harry's age is 19
Emma's age is 20
John's age is 18

write your code here: Coding Playground

Example 2 : Python zip enumerate

names = ['Mohan', 'Rohan', 'Yash']
ages = [34, 40, 22]

for i, (name, age) in enumerate(zip(names, ages)):
    print(i, name, age)

Output

0 Mohan 34
1 Rohan 40
2 Yash 22

Example 3 : Python zip() dictionary

stocks = ['realme', 'ibm', 'apple']
prices = [2175, 1127, 2750]
new_dict = {stocks: prices for stocks,
            prices in zip(stocks, prices)}
print(new_dict)

Output

{'realme': 2175, 'ibm': 1127, 'apple': 2750}

write your code here: Coding Playground