zip in Python

What is zip?

The zip() function combines elements from two or more iterables (like lists or tuples) into tuples, pairing elements by their index. It stops when the shortest iterable is exhausted.

Creating Zipped Objects

a = [1, 2, 3]
b = ["a", "b", "c"]
zipped = zip(a, b)
print(list(zipped))  # Output: [(1, 'a'), (2, 'b'), (3, 'c')]

Examples

# 1. Basic zip usage
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 95]
for name, score in zip(names, scores):
    print(f"{name} scored {score}")
# Output:
# Alice scored 85
# Bob scored 90
# Charlie scored 95
  
# 2. Unequal length iterables
a = [1, 2]
b = ["x", "y", "z"]
print(list(zip(a, b)))  # Output: [(1, 'x'), (2, 'y')]
  
# 3. Converting zipped tuples back using zip and unpacking
zipped = zip([1, 2, 3], ['a', 'b', 'c'])
a1, b1 = zip(*zipped)
print(a1)  # Output: (1, 2, 3)
print(b1)  # Output: ('a', 'b', 'c')
  
# 4. Creating a dictionary using zip
keys = ['name', 'age', 'city']
values = ['Alice', 30, 'New York']
my_dict = dict(zip(keys, values))
print(my_dict)  # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
  
# 5. zipping more than two iterables
a = [1, 2]
b = [3, 4]
c = [5, 6]
print(list(zip(a, b, c)))  # Output: [(1, 3, 5), (2, 4, 6)]