Published on

What is the `zip` function in Python?

Authors
  • avatar
    Name
    hwahyeon
    Twitter

The zip function combines elements from multiple iterables. For example, if you pass two lists, it pairs the elements at the same index from each list into a tuple. The examples provide the best explanation! Let's take a look

Basic Example:

my_list = [1, 2, 3]
your_list = [40, 50, 60]
for i in zip(my_list, your_list):
    print(i)

output

(1, 40)
(2, 50)
(3, 60)

Combining Multiple Lists:

scores1 = [10, 20, 30, 40]
scores2 = [15, 25, 35, 45]
scores3 = [5, 10, 15, 20]
for score1, score2, score3 in zip(scores1, scores2, scores3):
    print(score1 + score2 + score3)

output

30
55
80
105

Creating a Dictionary from Key and Value Lists:

countries = ['Estonia', 'Germany', 'Greece']
capitals = ['Tallinn', 'Berlin', 'Athens']
country_capital_dict = dict(zip(countries, capitals))
print(country_capital_dict)

output

{'Estonia': 'Tallinn', 'Germany': 'Berlin', 'Greece': 'Athens'}