An inventory report pairs product codes, quantities and prices.
What You Need to Understand
Use zip() to iterate over matching positions in two or more lists. Use strict=True if the data contract requires every source to have the same length.
When to Use It
An inventory report pairs product codes, quantities and prices.
Step-by-Step Python Example
products = ["P-01", "P-02"]
quantities = [3, 5]
unit_prices = [2.5, 1.75]
for product, quantity, unit_price in zip(products, quantities, unit_prices, strict=True):
print(product, f"{quantity * unit_price:.2f}")
How the Example Works
Each iteration unpacks one aligned record, calculates a line total and displays it.
Example Output
P-01 7.50
P-02 8.75
[('A', 100), ('B', 200)]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
print(list(zip(["A", "B"], [100, 200], strict=True)))
Important Behavior and Edge Cases
A silent mismatch can associate incomplete records; zip(strict=True) catches uneven input lengths.
Try It Yourself
Add a third product without adding its price and observe the strict-length error.
Common Beginner Mistakes
- A silent mismatch can associate incomplete records;
zip(strict=True)catches uneven input lengths. - Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
- Use
zip()to iterate over matching positions in two or more lists. - Each iteration unpacks one aligned record, calculates a line total and displays it.
- A silent mismatch can associate incomplete records;
zip(strict=True)catches uneven input lengths.