Nearby lessons

48 of 159

Python - zip() Function

📌 What You Will Learn
  • Explain how zip() combines iterables
  • Unpack zipped values in a for loop
  • Use zip() to create dictionaries
  • Handle iterables with unequal lengths
  • Convert a zip object into a list

Combining related sequences

zip() is useful when values at the same position belong together, such as names and scores.

Basic syntax

Use zip(iterable1, iterable2, ...). Each result item is a tuple containing one value from each input.

Loop over two lists together

🐍Code Cell
1names = ['Asha', 'Ben', 'Chen']
2scores = [85, 92, 78]
3 
4for name, score in zip(names, scores):
5 print(name, score)
Output
Asha 85
Ben 92
Chen 78

Inspecting the zip object

🐍Code Cell
1pairs = list(zip(['a', 'b'], [1, 2]))
2print(pairs)
Output
[('a', 1), ('b', 2)]

Building a dictionary

🐍Code Cell
1fields = ['name', 'age']
2values = ['Mira', 25]
3profile = dict(zip(fields, values))
4print(profile)
Output
{'name': 'Mira', 'age': 25}

Unequal lengths

Regular zip() stops at the shortest iterable, so extra values in longer inputs are ignored.

🐍Code Cell
1print(list(zip([1, 2, 3], ['a', 'b'])))
Output
[(1, 'a'), (2, 'b')]

Unzipping pairs

Use the unpacking operator with zip() to separate pairs back into columns.

🐍Code Cell
1pairs = [('A', 10), ('B', 20)]
2letters, numbers = zip(*pairs)
3print(letters)
4print(numbers)
Output
('A', 'B')
(10, 20)

When to use zip_longest()

Import zip_longest() from itertools when every item from unequal-length inputs should be processed with a fill value.

📝 Key Takeaways
  • zip() groups corresponding elements into tuples
  • The result is a lazy zip iterator
  • Iteration stops when the shortest iterable is exhausted
  • dict(zip(keys, values)) is a convenient dictionary pattern
  • Use itertools.zip_longest() when missing values should be retained

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8