🕯️ Magic Note
When you call zip(a, b), Python returns an iterator that produces tuples. The first tuple is (a[0], b[0]). The second is (a[1], b[1]). This continues until one of the iterables runs out of items. The remaining elements from longer iterables are ignored.
- Works with any number of iterables: zip(a, b, c, d)
- Stops at the shortest iterable by default
- Returns an iterator, use list(zip(a, b)) to see all pairs at once
- Use itertools.zip_longest() to keep all elements with fill values
| Input A | Input B | zip() Output |
|---|---|---|
| [1, 2, 3] | [“a”, “b”, “c”] | (1, “a”), (2, “b”), (3, “c”) |
| [“x”, “y”] | [10, 20, 30] | (“x”, 10), (“y”, 20) |
| [“name”, “age”] | [“Ali”, 25] | (“name”, “Ali”), (“age”, 25) |
| [1, 2, 3] | [4, 5, 6] | (1, 4), (2, 5), (3, 6) |
Python
# Pairing names with scores
students = [“Elena”, “Marcus”, “Sofia”]
scores = [92, 87, 95]
for student, score in zip(students, scores):
print(f”{student}: {score}”)
# Output: Elena: 92
# Output: Marcus: 87
# Output: Sofia: 95
Python
# Creating a dictionary from two lists
keys = [“name”, “element”, “level”]
values = [“Feloriya”, “shadow”, 7]
spellbook = dict(zip(keys, values))
print(spellbook)
# Output: {“name”: “Feloriya”, “element”: “shadow”, “level”: 7}
Python
# Unzipping a list of pairs
pairs = [(“a”, 1), (“b”, 2), (“c”, 3)]
letters, numbers = zip(*pairs)
print(letters)
# Output: (“a”, “b”, “c”)
print(numbers)
# Output: (1, 2, 3)
- Assuming zip() keeps all elements, forgetting it stops at the shortest iterable without warning
- Calling zip() on huge iterables without iterating, zip returns an iterator not a list
- Forgetting to unpack tuples when looping, writing for pair in zip(a,b) then accessing pair[0] and pair[1] instead of unpacking
⚡ Whisper
Every side has its match. The zipper finds the partner for each tooth. Walk together. Step by step. Paired perfectly. When one side ends, the journey stops. No element left behind, no element left alone.