Python zip() Function

The Python zip() function aggregates elements from two or more iterables and zip them into a single iterable. The result of the zip() function is an iterator of tuples that contains elements from each iterable you have passed into the zip(). This iterator can later be converted to any desired type of iterable like a list, dictionary, etc based on the requirement.

first_name = ['John', 'James', 'Jennifer']
last_name  = ['Doe', 'Bond', 'Smith']

students = zip(first_name, last_name)

print(list(students))

# Output:
# [('John', 'Doe'), ('James', 'Bond'), ('Jennifer', 'Smith')]

Syntax of the zip() Function

The syntax of the zip() function is as follows:

zip(*iterables)

zip() Function Parameters

The zip() function takes in iterables as arguments such as lists, sets, tuples, dictionaries, etc. It can take any number of iterables at a time.


zip() Function Return Value

The zip() function returns a zip object. This zip object is basically an iterator containing items from all the iterables passed to the zip() function. This zip object can later be converted to any type of iterable such as list, dictionary, set, etc.


Understanding the zip() Function

At the beginning of this tutorial, we learned that the Python zip() function aggregates elements from two or more iterables and results into a single iterator. Now, let’s understand it with the help of a real-world example.

Suppose, you have two lists containing the first names and last names of university students. Your task is to combine the first names with the corresponding last names. How would you do that? Well, the answer is the Python zip() function.

The Python zip() function aggregates elements that are on the same index in different iterables and returns an iterator containing all such combinations. See the example below:

Example 1: Combining first name and last name

first_name = ['John', 'James', 'Jennifer']
last_name  = ['Doe', 'Bond', 'Smith']

students = zip(first_name, last_name)

print(list(students))

Output:

[('John', 'Doe'), ('James', 'Bond'), ('Jennifer', 'Smith')]

Example 2: Combining first name, last name and age

In the previous example, we zipped the first names with their corresponding last names using the zip().

Now, let’s add one more field, the age of the students with their corresponding first and last names. To do that we have to pass one more parameter i.e. age to the zip() function and our task will be done.

first_name = ['John', 'James', 'Jennifer']
last_name  = ['Doe', 'Bond', 'Smith']
age = [18, 19, 20]

students = zip(first_name, last_name, age)

print(list(students))

Output:

[('John', 'Doe', 18), ('James', 'Bond', 19), ('Jennifer', 'Smith', 20)]

Passing One Argument

The zip() function can also take just one argument. In this case, the zip() function returns an iterator that contains a list of 1-item tuples.

Example:

nums = [1, 2, 3, 4]

a = zip(nums)

print(list(a))

Output:

[(1,), (2,), (3,), (4,)]

Passing No Arguments

You can also call the zip() function without passing any arguments to it. In this case, the zip() function returns an empty iterator.

Example:

a = zip()
print(list(a))

Output:

[ ]

Passing Arguments of Unequal Length

There might be situations where the length of the iterables that we are passing as the arguments is unequal. In such cases, the zip() function returns an iterator which has the same length as the shortest iterable. The remaining items in the longer iterables are completely ignored by the zip() function.

Example:

numbers = [1, 2, 3]
letters = ['a', 'b', 'c', 'd', 'e', 'f']

zipped = zip(numbers, letters)

print(list(zipped))

Output:

[(1, 'a'), (2, 'b'), (3, 'c')]

In the above example, the length of the shortest iterable is 3. Therefore only the first three items from both the iterables are considered. The remaining items(‘d’, ‘e’ & ‘f’) have no match therefore they are completely ignored.


Creating Dictionaries using zip()

Sometimes, you might have a requirement where you need to build a dictionary from two similar types of sequences. This can be easily achieved using the zip() function.

In the below example, we have two lists containing information of a student. We have zipped these two lists and created a single dictionary from them.

Example:

keys = ['first_name', 'last_name', 'age', 'gender']
values = ['John', 'Doe', 23, 'Male']

student = zip(keys, values)

print(dict(student))

Output:

{'first_name': 'John', 'last_name': 'Doe', 'age': 23, 'gender': 'Male'}

Using for loop with zip()

In Python, you might have come across a situation where you have to iterate over multiple iterables at the same time. For example, iterating through multiple lists, tuples, sets, or any other sequence. This can be very easily achieved using the zip() function.

As the zip() function returns a series of tuples. Therefore, we can easily unpack these tuple items in the declaration of the for loop.

Example 1: Traversing lists in parallel

keys = ['first_name', 'last_name', 'age', 'gender']
values = ['John', 'Doe', 23, 'Male']

for key, value in zip(keys, values):
    print(key,': ',value)

Output:

first_name :  John
last_name :  Doe
age :  23
gender :  Male

Example 2: Traversing dictionaries in parallel

Similar to the lists, we can traverse multiple dictionaries in parallel as well. But to access key-value pairs from all dictionaries, we have to make use of the items() function. See implementation in the below example:

stud1 = {'first_name': 'John', 'last_name': 'Doe', 'age': 23}
stud2 = {'first_name': 'Jennifer', 'last_name': 'Smith', 'age': 24}

for (k1, v1), (k2, v2) in zip(stud1.items(), stud2.items()):
    print(k1,': ', v1)
    print(k2,': ', v2)

Output:

first_name :  John
first_name :  Jennifer
last_name :  Doe
last_name :  Smith
age :  23
age :  24

Unzipping Values

Till now, we have understood a lot about zipping the sequences. But now the question that comes in mind is ‘How can we unzip a sequence?’ Is there any inbuilt method that does just the reverse of the zip()? Well, there is no such inbuilt method in Python.

The answer to this question is the zip() function itself. The zip() function can perform both zipping and unzipping of sequences. To unzip a sequence we have to use the zip() function with the unpacking operator *. See the example given below:

Example:

student = [('first_name', 'John'), ('last_name', 'Doe'), ('age', 23)]

keys, values = zip(*student)

print('keys =', keys)
print('values =', values)

Output:

keys = ('first_name', 'last_name', 'age')
values = ('John', 'Doe', 23)

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts