How to zip two lists in Python?

“Zip” function in Python is a built-in method that allows users to combine two lists into one list of tuples. This process is known as zipping. It takes the corresponding elements from each list and puts them together in a tuple, creating a new list. To use the zip function, simply pass in the two lists as parameters, and it will return a zip object that can be converted into a list. This method is commonly used in data manipulation and analysis, as it provides an efficient way to merge two sets of data. Additionally, the zip function can also be used to zip more than two lists, as long as they have the same length.

Zip Two Lists in Python


Often you might be interested in zipping (or “merging”) together two lists in Python. Fortunately this is easy to do using the zip() function.

This tutorial shows several examples of how to use this function in practice.

Example 1: Zip Two Lists of Equal Length into One List

The following syntax shows how to zip together two lists of equal length into one list:

#define list a and list b
a = ['a', 'b', 'c']b = [1, 2, 3]

#zip the two lists together into one listlist(zip(a, b))

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

Example 2: Zip Two Lists of Equal Length into a Dictionary

The following syntax shows how to zip together two lists of equal length into a dictionary:

#define list of keys and list of values keys = ['a', 'b', 'c']
values = [1, 2, 3]

#zip the two lists together into one dictionarydict(zip(keys, values)) 

{'a': 1, 'b': 2, 'c': 3}

Example 3: Zip Two Lists of Unequal Length

If your two lists have unequal length, zip() will truncate to the length of the shortest list:

#define list a and list b
a = ['a', 'b', 'c', 'd']b = [1, 2, 3]

#zip the two lists together into one listlist(zip(a, b))

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

If you’d like to prevent zip() from truncating to the length of the shortest list, you can instead use the function from the itertools library.

By default, this function fills in a value of “None” for missing values:

from itertools import zip_longest

#define list a and list b
a = ['a', 'b', 'c', 'd']b = [1, 2, 3]

#zip the two lists together without truncating to length of shortest listlist(zip_longest(a, b))

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

However, you can use the fillvalue argument to specify a different fill value to use:

#define list a and list b
a = ['a', 'b', 'c', 'd']b = [1, 2, 3]

#zip the two lists together, using fill value of '0'list(zip_longest(a, b, fillvalue=0))

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

You can find the complete documentation for the zip_longest() function .

x