Combines multiple iterables together
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)
Parameter | Condition | Description |
iterables | Optional | One or more iterables (list, tuple, dictionary etc.) to be joined together |
Basic Example
# Combine two lists together
x = [1, 2, 3]
y = ['one', 'two', 'three']
result = zip(x, y)
print(list(result))
# Prints [(1, 'one'), (2, 'two'), (3, 'three')]
Multiple Iterables
You can pass as many iterables you want to the zip()
function.
# Zip three lists
x = [1, 2, 3]
y = ['one', 'two', 'three']
z = ['I', 'II', 'III']
result = zip(x, y, z)
print(list(result))
# Prints [(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.
# Iterable 'y' 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(list(result))
# Prints [(1, 'one', 'I'), (2, 'two', 'II')]
Unzip/Unpack Zipped Items
zip()
in conjunction with the * operator can be used to unzip a list:
# zip
x = [1, 2, 3]
y = ['one', 'two', 'three']
result = zip(x, y)
# unzip
a, b = zip(*result)
print(a)
# Prints (1, 2, 3)
print(b)
# Prints ('one', 'two', 'three')
Common Use
You can create a dictionary with list of zipped keys and values.
keys = ['name', 'age']
values = ['Bob', 25]
D = dict(zip(keys, values))
print(D)
# Prints {'age': 25, 'name': 'Bob'}
Using zip()
function you can loop through multiple lists at once.
name = ['Bob', 'Sam', 'Max']
age = [25, 35, 30]
for x, y in zip(name, age):
print(x, y)
# Prints Bob 25
# Prints Sam 35
# Prints Max 30