Python zip() Function

Combines multiple iterables together

Basic Example

Example: Combine two lists together

x = [1, 2, 3]
y = ['one', 'two', 'three']

result = zip(x, y)
print(result)

Output:

[(1, 'one'), (2, 'two'), (3, 'three')]

Usage

The zip() function combines items from each of the specified iterables.

The return value is a list of tuples where the items of each passed iterable at same index are paired together.

Syntax

zip(iterables)

Parameters

Python zip() function parameters
ParameterConditionDescription
iterablesOptionalOne or more iterables (list, tuple, dictionary etc.) to be joined together

Multiple Iterables

You can pass as many iterables you want to the zip() function.

Example: Zip three lists

x = [1, 2, 3]
y = ['one', 'two', 'three']
z = ['I', 'II', 'III']

result = zip(x, y, z)
print(result)

Output:

[(1, 'one', 'I'), (2, 'two', 'II'), (3, 'three', 'III')]

Iterables with Different Length

If you pass iterables having different length, the iterable with least items decides the length of the resulting iterable.

Example: Iterable ‘y’ with least items decides the length of the resulting iterable

x = [1, 2, 3, 4]
y = ['one', 'two']
z = ['I', 'II', 'III']

result = zip(x, y, z)
print(result)

Output:

[(1, 'one', 'I'), (2, 'two', 'II')]

Unzip/Unpack Zipped Items

zip() in conjunction with the * operator can be used to unzip a list:

Examples: Unzip Zipped Items

# zip
x = [1, 2, 3]
y = ['one', 'two', 'three']

result = zip(x, y)

print(result)   # [(1, 'one'), (2, 'two'), (3, 'three')]
# unzip
a, b = zip(*result)

print(a)    # (1, 2, 3)
print(b)    # ('one', 'two', 'three')

Common Use

You can create a dictionary with list of zipped keys and values.

Example: Create a dictionary with list of zipped keys and values

keys = ['name', 'age']
values = ['Bob', 25]

D = dict(zip(keys, values))
print(D)    # {'age': 25, 'name': 'Bob'}

Using zip() function you can loop through multiple lists at once.

Example: Loop through two lists at once

name = ['Bob', 'Sam', 'Max']
age = [25, 35, 30]

for x, y in zip(name, age):
    print(x, y)

Output:

# Bob 25
# Sam 35
# Max 30