The Magic zip() in Python
Zipping Two Lists
You can use zip() to combine two lists element-wise into pairs.
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
zipped = zip(list1, list2)
print(list(zipped)) # [(1, 'a'), (2, 'b'), (3, 'c')]
Unzipping a Zipped Object
You can "unzip" using zip(*zipped_object)
to separate a zipped list back into individual lists.
zipped = [(1, 'a'), (2, 'b'), (3, 'c')]
list1, list2 = zip(*zipped)
print(list1) # (1, 2, 3)
print(list2) # ('a', 'b', 'c')
Iterating Over Multiple Lists
You can use zip()
to loop over multiple lists simultaneously.
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 90, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# Output:
# Alice: 85
# Bob: 90
# Charlie: 78
Using zip() with Different Lengths
If the lists have different lengths, zip() stops when the shortest list is exhausted.
list1 = [1, 2, 3, 4]
list2 = ['a', 'b', 'c']
zipped = zip(list1, list2)
print(list(zipped)) # [(1, 'a'), (2, 'b'), (3, 'c')]
Zipping More Than Two Lists
You can zip together more than two lists at once.
a = [1, 2, 3]
b = ['x', 'y', 'z']
c = [0.1, 0.2, 0.3]
zipped = zip(a, b, c)
print(list(zipped)) # [(1, 'x', 0.1), (2, 'y', 0.2), (3, 'z', 0.3)]
Creating Dictionaries with zip()
You can create a dictionary by zipping two lists, one as keys and the other as values.
keys = ['name', 'age', 'city']
values = ['Alice', 25, 'New York']
dictionary = dict(zip(keys, values))
print(dictionary) # {'name': 'Alice', 'age': 25, 'city': 'New York'}
The zip() function is versatile for combining and handling multiple iterables efficiently.