🐍 Python Everyday — ✨ zip(): Work with Related Collections
Posted on: November 27, 2026
Description:
Three café tables placed three orders. Table numbers are in one list and drinks are in another. Which table gets the tea? Read the second item from each list.
| Position | Table | Drink |
|---|---|---|
| First | 4 | latte |
| Second | 7 | tea |
| Third | 9 | mocha |
Print one ticket per pair
tables = [4, 7, 9]
drinks = ["latte", "tea", "mocha"]
for table, drink in zip(tables, drinks):
print(f"Table {table}: {drink}")
Each pass takes the next item from each input. Python unpacks the resulting tuple into table and drink, so the second pass prints Table 7: tea. This works because the two collections describe orders in the same sequence. If someone sorts just the drinks, the loop will still run and could send the right drink to the wrong table.
What if you read the pairs twice?
pairs = zip(tables, drinks)
print(next(pairs)) # (4, 'latte')
print(list(pairs)) # [(7, 'tea'), (9, 'mocha')]
print(list(pairs)) # []
A zip object is an iterator. Reading a pair advances it. To revisit all three tickets, save list(zip(tables, drinks)) before consuming any pairs, or call zip(tables, drinks) again on the original lists.
Decide what a missing drink means
If the drinks list ends after tea, ordinary zip() yields two pairs and stops. Table 9 is left without a ticket. That behaviour fits a task where only complete pairs count. In this café, each table should have a drink, so a missing entry should put the batch on hold.
short_menu = ["latte", "tea"]
try:
tickets = list(zip(tables, short_menu, strict=True))
except ValueError:
print("Batch on hold: table and drink counts differ.")
else:
for table, drink in tickets:
print(f"Table {table}: {drink}")
Why build the list first? Strict mode discovers a length mismatch during iteration. If you printed inside the strict loop, the first two tickets could already be out before Python raised ValueError. For this small batch, consuming the iterator first means printing begins only after the length check succeeds. The strict argument requires Python 3.10 or later.
No comments yet. Be the first to comment!