This guide explains zip(strict=true): catch unequal sequence lengths through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.
What You Will Learn
zip(..., strict=True) combines multiple iterables and raises ValueError if their lengths differ. This is valuable when silently dropping extra data would corrupt a report.
When and Why to Use It
The following example focuses on a practical use of zip(strict=True): Catch Unequal Sequence Lengths.
Step-by-Step Example
product_names = ["Pen", "Paper"]
prices = [3, 5]
print(list(zip(product_names, prices, strict=True)))
try:
print(list(zip(product_names, [3], strict=True)))
except ValueError:
print("Input lengths do not match")
Understanding the Example
The equal-length lists produce two pairs. The unequal-length call raises ValueError when consumed, making the missing price visible.
Expected Output
[('Pen', 3), ('Paper', 5)]
Input lengths do not match
Important Behavior and Edge Cases
The default zip truncates to the shortest iterable. The strict check runs during iteration, not when the zip object is created.
Try It Yourself
Pair customer IDs with email addresses and detect a missing address.
Common Beginner Mistakes
- The default zip truncates to the shortest iterable. The strict check runs during iteration, not when the zip object is created.
- Confusing a returned value with printed output, or failing to verify a function’s behavior with different input values.
- Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.
Key Takeaways
- zip(..., strict=True) combines multiple iterables and raises ValueError if their lengths differ.
- The equal-length lists produce two pairs.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.