Browse topics

enumerate and zip

Version
3.14
Review
Draft

Summary#

enumerate pairs each item with a running count. zip walks several iterables in parallel and yields one tuple per position.

Syntax#

python
for index, item in enumerate(items, start=0):
    pass

for first, second in zip(left, right, strict=True):
    pass

Example#

python
names = ["api", "worker", "cron"]
ports = [8000, 8001]

for number, name in enumerate(names, start=1):
    print(number, name)

print(list(zip(names, ports)))

try:
    list(zip(names, ports, strict=True))
except ValueError:
    print("zip length mismatch")

keys, values = zip(*[("a", 1), ("b", 2)])
print(keys, values)

Expected output#

Text
1 api
2 worker
3 cron
[('api', 8000), ('worker', 8001)]
zip length mismatch
('a', 'b') (1, 2)

Common mistakes#

By default zip stops at the shortest input, so extra items may be omitted. Pass strict=True when equal lengths are required. The error appears only when iteration reaches the mismatch. Use itertools.zip_longest to pad shorter inputs instead.

Version applicability#

enumerate(..., start=...), iterator-based zip and unpacking with zip(*pairs) work on all Python 3 releases. The strict argument of zip was added in Python 3.10 and sets the minimum for the example.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0