Python zip()
Tutorial
The zip()
function in Python combines multiple iterables (lists, tuples, dictionaries, etc.) element-wise into tuples.
It is commonly used for:
✅ Pairing elements from multiple lists
✅ Iterating over multiple lists simultaneously
✅ Unzipping (extracting back original lists)
✅ Transforming a Transport Matrix
Summary of zip()
Usage
Use Case | Code Example |
---|---|
Pair elements | zip(list1, list2) |
Loop over pairs | for a, b in zip(list1, list2): |
Unzip data | zip(*zipped_data) |
Handle different lengths | itertools .zip_longest(list1, list2, fillvalue='?') |
Sort together | sorted(zip(scores, names)) |
Create a dictionary | dict(zip(keys, values)) |
Extract transport matrix columns | list(zip(*matrix)) |
1️⃣ Basic Usage of zip()
🟢 Combining Two Lists
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
zipped = zip(list1, list2)
print(list(zipped))
# Output: [(1, 'a'), (2, 'b'), (3, 'c')]
✅ Pairs elements from both lists into tuples.
2️⃣ Iterating Over zip()
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 88]
for name, score in zip(names, scores):
print(f"{name} scored {score}")
Output:
Alice scored 85
Bob scored 90
Charlie scored 88
✅ Iterates through paired elements from two lists.
3️⃣ Using zip(*iterable)
to Unzip Data
zipped_data = [(1, 'a'), (2, 'b'), (3, 'c')]
num, char = zip(*zipped_data)
print(num) # Output: (1, 2, 3)
print(char) # Output: ('a', 'b', 'c')
✅ Extracts back original lists using zip(*)
.
4️⃣ zip()
with Different Length Lists
list1 = [1, 2, 3]
list2 = ['a', 'b']
print(list(zip(list1, list2)))
# Output: [(1, 'a'), (2, 'b')] (Stops at shortest list)
✅ Stops at the shortest iterable to avoid IndexError
.
🔹 If you need to fill missing values, use itertools.zip_longest()
from itertools import zip_longest
print(list(zip_longest(list1, list2, fillvalue='?')))
# Output: [(1, 'a'), (2, 'b'), (3, '?')]
5️⃣ Sorting with zip()
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 88]
sorted_data = sorted(zip(scores, names), reverse=True)
print(sorted_data)
# Output: [(90, 'Bob'), (88, 'Charlie'), (85, 'Alice')]
✅ Sorts names
based on scores
using zip()
.
6️⃣ Creating a Dictionary Using zip()
keys = ['name', 'age', 'city']
values = ['Alice', 25, 'NYC']
person = dict(zip(keys, values))
print(person)
# Output: {'name': 'Alice', 'age': 25, 'city': 'NYC'}
✅ Efficiently converts two lists into a dictionary.
7️⃣ Using zip()
in Transport Matrix
The zip()
function can be used to transpose a transport matrix, making it easier to access columns instead of rows.
Example: Transport Matrix
cost_matrix = [
[8, 6, 10], # Factory X -> Store A, B, C
[9, 12, 7] # Factory Y -> Store A, B, C
]
# Transpose the matrix using zip()
transposed_matrix = list(zip(*cost_matrix))
# Display the transposed transport matrix
for column in transposed_matrix:
print(column)
Output:
(8, 9)
(6, 12)
(10, 7)
✅ zip(*cost_matrix)
converts rows into columns, making store-wise access easier.