search

What is the use of the "zip" function in Python?

The zip() function in Python is used to combine elements from multiple iterables (such as lists, tuples, or strings) into a single iterator. It takes iterables as input and returns an iterator of tuples, where each tuple contains elements from the corresponding positions of the input iterables.

Here's the basic syntax of the zip() function:

zip(*iterables)
  • *iterables represents one or more iterable objects that you want to zip together.

The resulting iterator stops when the shortest input iterable is exhausted. This means that if the input iterables have different lengths, the resulting iterator will contain tuples up to the length of the shortest input iterable.

Let's explore some examples to understand the usage of the zip() function:

  1. Example with lists:
fruits = ['apple', 'banana', 'orange']
colors = ['red', 'yellow', 'orange']

# Using zip() with lists
for fruit, color in zip(fruits, colors):
    print(fruit, "is", color)

Output:

apple is red
banana is yellow
orange is orange

In this example, the zip() function combines elements from the fruits and colors lists into tuples. The for loop iterates over the resulting iterator, and each tuple is unpacked into the variables fruit and color.

  1. Example with different-length iterables:
fruits = ['apple', 'banana', 'orange']
prices = [1.0, 0.8]

# Using zip() with different-length iterables
for fruit, price in zip(fruits, prices):
    print(fruit, "is priced at", price)

Output:

apple is priced at 1.0
banana is priced at 0.8

In this example, the zip() function stops when it reaches the end of the shortest input iterable (prices). The iteration is only performed for the corresponding elements that exist in both iterables.

  1. Example with unpacking and zip():
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]

# Using zip() and unpacking
person_info = zip(names, ages)
person1, person2, person3 = person_info

print(person1)
print(person2)
print(person3)

Output:

('Alice', 25)
('Bob', 30)
('Charlie', 35)

In this example, the zip() function combines the names and ages lists into an iterator of tuples. The person_info variable holds the iterator. Then, the person_info iterator is unpacked into individual variables (person1, person2, person3), which hold each tuple.

The zip() function is commonly used when you need to process multiple iterables simultaneously. It is particularly useful when you want to iterate over multiple lists or tuples in a parallel manner, combining related elements from different sequences.

Related Questions You Might Be Interested