1. Combining Two Lists
Use case: Merging two lists element-wise.
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
combined = list(zip(names, ages))
print(combined)
[('Alice', 25), ('Bob', 30), ('Charlie', 35)]
2. Unzipping Lists
Use case: Splitting paired data into separate lists.
combined = [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
names, ages = zip(*combined)
print(names)
print(ages)
('Alice', 'Bob', 'Charlie')
(25, 30, 35)
3. Iterating Over Multiple Lists Simultaneously
Use case: Useful when you need to iterate through multiple lists at the same time.
subjects = ['Math', 'Science', 'English']
scores = [88, 92, 85]
for subject, score in zip(subjects, scores):
print(f"{subject}: {score}")
Math: 88
Science: 92
English: 85
4. Creating Dictionaries
Use case: Creating dictionaries from two lists: one for keys, one for values.
keys = ['name', 'age', 'city']
values = ['Alice', 25, 'New York']
dictionary = dict(zip(keys, values))
print(dictionary)
{'name': 'Alice', 'age': 25, 'city': 'New York'}
5. Combining Multiple Lists
Use case: Zipping more than two lists together.
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = [True, False, True]
combined = list(zip(list1, list2, list3))
print(combined)
[(1, 'a', True), (2, 'b', False), (3, 'c', True)]
6. Handling Different Length Iterables
Use case: When lists have different lengths, zip() stops at the shortest one.
list1 = [1, 2, 3]
list2 = ['a', 'b']
combined = list(zip(list1, list2))
print(combined)
[(1, 'a'), (2, 'b')]
7. Working with Ranges
Use case: Zipping together ranges or sequences.
numbers = range(1, 4)
letters = ['a', 'b', 'c']
result = list(zip(numbers, letters))
print(result)
[(1, 'a'), (2, 'b'), (3, 'c')]
8. Comparing Elements of Two Lists
Use case: Zipping two lists to compare elements.
list1 = [1, 2, 3]
list2 = [1, 4, 3]
comparison = [a == b for a, b in zip(list1, list2)]
print(comparison)
[True, False, True]
9. Transpose a Matrix
Use case: Use zip() to transpose rows and columns of a 2D matrix.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
transposed = list(zip(*matrix))
print(transposed)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
10. Zipping with Enumerate
Use case: Zipping with an enumerated list for indexed pairings.
data = ['apple', 'banana', 'cherry']
indexed_data = list(zip(range(1, len(data) + 1), data))
print(indexed_data)
[(1, 'apple'), (2, 'banana'), (3, 'cherry')]
0 Comments:
Post a Comment