Python zip() built-in function

From the Python 3 documentation

Iterate over several iterables in parallel, producing tuples with an item from each one.

Introduction

The zip() function in Python is a built-in function that takes two or more iterables (like lists, tuples, or strings) and aggregates them into a single iterator of tuples. Each tuple contains elements from all the input iterables at the same position.

Examples

furniture = ['table', 'chair', 'rack', 'shelf']
price = [100, 50, 80, 40]

for item, amount in zip(furniture, price):
    print(f'The {item} costs ${amount}')
The table costs $100
The chair costs $50
The rack costs $80
The shelf costs $40

Other Use Cases

The zip function in Python merges multiple iterables into tuples.

# Combining three lists
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = [True, False, True]

zipped = zip(list1, list2, list3)
print(list(zipped))
[(1, 'a', True), (2, 'b', False), (3, 'c', True)]

Unzipping

# Unzipping a zipped object
zipped = [(1, 'a'), (2, 'b'), (3, 'c')]
list1, list2 = zip(*zipped)
print(list1)
print(list2)
(1, 2, 3)
('a', 'b', 'c')

More Examples

Zipping with Different Lengths

zip stops creating tuples when the shortest iterable is exhausted.

numbers = [1, 2, 3]
letters = ['a', 'b']

for num, letter in zip(numbers, letters):
    print(f'{num} -> {letter}')
1 -> a
2 -> b

Using zip with Dictionaries

You can use zip to combine keys and values from two lists into a dictionary.

keys = ['name', 'age', 'city']
values = ['Alice', 25, 'New York']

my_dict = dict(zip(keys, values))
print(my_dict)
{'name': 'Alice', 'age': 25, 'city': 'New York'}

Using zip with List Comprehensions

You can use zip in list comprehensions for more concise code.

list1 = [1, 2, 3]
list2 = [4, 5, 6]

summed = [x + y for x, y in zip(list1, list2)]
print(summed)
[5, 7, 9]