A roster pairs names with the scores recorded in another list.
What You Need to Understand
zip(first, second, ...) produces tuples of matching-position elements from its inputs. By default it stops as soon as the shortest iterable ends; strict=True raises a ValueError if lengths differ.
When to Use It
A roster pairs names with the scores recorded in another list.
Step-by-Step Python Example
names = ["Maya", "Liam", "Noa"]
scores = [88, 91, 79]
for name, score in zip(names, scores, strict=True):
print(name, score)
How the Example Works
Each iteration produces a (name, score) pair. strict=True makes unexpected missing scores an error instead of silently dropping records.
Example Output
Maya 88
Liam 91
Noa 79
[('A', 2), ('B', 4)]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
print(list(zip(["A", "B"], [2, 4])))
Important Behavior and Edge Cases
A zip object is an iterator; it is normally consumed as it is used. Avoid silently truncating important datasets.
Try It Yourself
Combine product names and prices, then inspect the results of list(zip(...)).
Common Beginner Mistakes
- A zip object is an iterator; it is normally consumed as it is used. Avoid silently truncating important datasets.
- Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
zip(first, second, ...)produces tuples of matching-position elements from its inputs.- Each iteration produces a
(name, score)pair. - A zip object is an iterator; it is normally consumed as it is used.