What does the zip function do in Python and how to use it to stitch two lists?

Problem:

We need to zip two lists into one using Python. How do we do that?

Solution:

We’ll use the buil-in zip() function in Python, which would pretty much do the job for us. In this quick tutorial we’ll learn about how to we can utilize the zip in our code.

Zip function in Python

The zip() function in Python is used to join multiple lists into a list that contains elements from the multiple lists. We will look at an example code to see how zip() works.

Code:

def getzipped(value1, value2):
    zip_object = zip(value1,value2)
    zip_list = list(zip_object)
    return zip_list
names = ["John", "Vikram", "Bahu"]
rank = [4,5,6]
print("Names:",names)
print("Ranks:",rank)
print("Zip of two lists are:", getzipped(names,rank))

Output:

Names: ['John', 'Vikram', 'Bahu']
Ranks: [4, 5, 6]
Zip of two lists are: [('John', 4), ('Vikram', 5), ('Bahu', 6)]

Practical example: joining two lists of unequal length

When two unequal lists are zipped using the zip() function, we will get an output of the shortest list length. Let’s see a small example.

Code:

names = ["John","Vikram","Bahu"]
ranks = [1,2]
print(list(zip(names,ranks)))

Output:

[('John', 1), ('Vikram', 2)]

As you see, the ranks list contains the shortest length, Bahu from the names list was ignored by the zip() function. Let us see how we can overcome this issue.

Use itertools.zip_longest():

Using the itertools.zip_longest() function, we can replace missing values with a provided string passed in the fillvalue argument.

Code:

from itertools import zip_longest 
def getzipped(value1, value2):
    zip_object = zip_longest(value1, value2, fillvalue='?')
    zip_list = list(zip_object)
    return zip_list
names = ["John", "Vikram", "Bahu"]
rank = [1,2]
print("Names:",names)
print("Ranks:",rank)
print("Zip of two lists are:", getzipped(names,rank))

Output:

Names: ['John', 'Vikram', 'Bahu']
Ranks: [1, 2]
Zip of two lists are: [('John', 1), ('Vikram', 2), ('Bahu', '?')]

Note:

  • Make sure to import itertools from itertools import zip_longest.