Python zip(): Combine Multiple Iterables into Tuples

The zip() function pairs elements from multiple iterables (lists, tuples, sets, etc.) into tuples. It’s useful for iterating over multiple lists in parallel, creating key-value pairs, and data processing.

Example

names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 78]

zipped = zip(names, scores)
print(list(zipped))

Output:

[('Alice', 85), ('Bob', 90), ('Charlie', 78)]

Pairs corresponding elements into tuples.

Syntax

zip(iterable1, iterable2, ...)
  • iterable1, iterable2, … → Sequences to combine.
  • Returns → A zip object (iterator of tuples).

1. Zipping Two Lists Together

students = ["Alice", "Bob", "Charlie"]
marks = [80, 85, 90]

paired = zip(students, marks)
print(list(paired))  
# Output: [('Alice', 80), ('Bob', 85), ('Charlie', 90)]

2. Converting zip() to a Dictionary

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

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

3. Iterating Over Multiple Lists in Parallel

fruits = ["apple", "banana", "cherry"]
colors = ["red", "yellow", "purple"]

for fruit, color in zip(fruits, colors):
    print(f"{fruit} is {color}")

Output:

apple is red
banana is yellow
cherry is purple

4. Unzipping (Reverse zip())

zipped_data = [("Alice", 80), ("Bob", 85), ("Charlie", 90)]
names, scores = zip(*zipped_data)

print(names)   # Output: ('Alice', 'Bob', 'Charlie')
print(scores)  # Output: (80, 85, 90)

Key Notes

  • Pairs elements from multiple iterables into tuples.
  • Stops at the shortest iterable unless using zip_longest().
  • Works with lists, tuples, dictionaries, and sets.
  • Use zip(*zipped_list) to unzip.

By using zip(), you can combine data easily, iterate over multiple lists efficiently, and manipulate paired elements effectively. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top