Lesson explanation
After this lesson, you will be able to:
zip() without manually indexing them.zip() stops at the shortest input and what that means for missing data.enumerate() and zip() to number paired records.Sometimes a program receives related data in parallel sequences: one contains names and another contains values in the same order. zip() pairs them by position. Each pair can be unpacked directly in a for loop.
for item, value in zip(items, values):
...Important: ordinary zip() stops when its shortest input runs out. It does not invent placeholder values for missing entries. When lengths must match exactly, check them separately before pairing; otherwise, extra values are ignored.
You already know enumerate() for numbering values. Put it around zip() when you need a 1-based display number and both values. Python's tuple unpacking lets the loop receive all three cleanly.
For aligned, unique keys, dict(zip(keys, values)) also constructs a lookup. Beware: duplicate keys are overwritten by the last paired value.
zones = ["west", "east"]
replicas = [2, 4]
for zone, count in zip(zones, replicas):
print(f"{zone}: {count} replicas")Output:
west: 2 replicas
east: 4 replicasEach loop step gives you one aligned pair.
teams = ["alpha", "beta", "gamma"]
regions = ["eu", "us"]
print(list(zip(teams, regions)))Output:
[('alpha', 'eu'), ('beta', 'us')]gamma is not paired: there is no third region.
services = ["cache", "api"]
ports = [6379, 8080]
for number, (service, port) in enumerate(zip(services, ports), start=1):
print(f"{number}. {service} uses {port}")Output:
1. cache uses 6379
2. api uses 8080The parentheses around (service, port) unpack the pair inside the numbered item.
features = ["search", "export"]
limits = [20, 5]
lookup = dict(zip(features, limits))
print(lookup)Output:
{'search': 20, 'export': 5}For duplicate feature names, the later paired limit would replace the earlier one.
| Goal | Pattern |
|---|---|
| Pair aligned values | zip(first, second) |
| Iterate over pairs | for left, right in zip(...): |
| Number paired values | enumerate(zip(...), start=1) |
| Build a dictionary | dict(zip(keys, values)) |
| Avoid silently missing data | Check lengths before using zip() when required |
zip() is not a full outer join: it stops at the shortest input.enumerate(zip(...)) produces a number and a pair; unpack both levels correctly.