15.3 C
London
Tuesday, June 17, 2025
HomePythonOperations in PythonHow to Zip Two Lists in Python

How to Zip Two Lists in Python

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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 list
list(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 dictionary
dict(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 list
list(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 zip_longest() 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 list
list(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 here.

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories