Tony CantaveHow Python's enumerate and zip Cleaned Up My Loops
By Tony Cantave ·
When I started writing Python for real work, a lot of my loops looked like this:
stops = ["Depot", "Main St", "Elm St", "Harbor Rd"]
for i in range(len(stops)):
print(i, stops[i])It works. It is also the kind of code that hides bugs. You are managing an index by hand, and every time you write stops[i] you are trusting that i is valid for that list. Two built in functions, enumerate and zip, removed most of that from my scripts. Here is how I use them now.
enumerate: when you need the item and its position
enumerate hands you the position and the item together, so you never touch the index directly.
for number, stop in enumerate(stops, start=1):
print(f"Stop {number}: {stop}")The start=1 argument matters more than it looks. People count from 1. When I print a report or a validation message, "row 1" should mean the first row a person sees, not row zero.
That is exactly where I use it most: reporting problems in data files.
import csv
with open("orders.csv", newline="") as f:
reader = csv.DictReader(f)
for line_number, row in enumerate(reader, start=2):
if not row["order_id"].strip():
print(f"Line {line_number}: missing order_id")I start at 2 because line 1 of the file is the header. Now the message points to the exact line someone will see when they open the file in a spreadsheet. That small detail saves a lot of back and forth.
zip: walking two lists side by side
zip pairs items from two or more iterables, position by position.
names = ["Line A", "Line B", "Line C"]
planned = [120, 95, 140]
actual = [118, 101, 140]
for name, plan, done in zip(names, planned, actual):
status = "on target" if done >= plan else "short"
print(f"{name}: planned {plan}, actual {done}, {status}")Compare that to the index version, where you write planned[i] and actual[i] and hope the three lists line up. With zip, the pairing is the whole point of the line, so it reads like what it does.
zip also builds dictionaries quickly:
headers = ["sku", "qty", "bin"]
values = ["A100", "12", "B4"]
record = dict(zip(headers, values))
# {'sku': 'A100', 'qty': '12', 'bin': 'B4'}The trap: zip stops at the shortest list
This is the one that bit me. If the lists are different lengths, zip quietly stops when the shortest one runs out. No error, no warning. If one export is missing a row, you lose data silently.
Since Python 3.10 there is a fix:
for name, plan in zip(names, planned, strict=True):
print(name, plan)With strict=True, a length mismatch raises a ValueError instead of being ignored. I now use it by default whenever the lists are supposed to match. If they do not, I want the script to stop and tell me, not hand me a report that looks complete but is not.
When different lengths are expected and I want to see every item, itertools.zip_longest fills the gaps:
from itertools import zip_longest
for a, b in zip_longest(["x", "y", "z"], ["x", "y"], fillvalue="(missing)"):
print(a, b)Putting them together
The two combine well. Here I compare two columns and report mismatches with human friendly row numbers:
expected = ["A100", "A101", "A102", "A103"]
scanned = ["A100", "A101", "A120", "A103"]
pairs = zip(expected, scanned, strict=True)
for row, (want, got) in enumerate(pairs, start=1):
if want != got:
print(f"Row {row}: expected {want}, scanned {got}")Output:
Row 3: expected A102, scanned A120A few lines of logic, no manual index, and it fails loudly if the lists do not match in length.
Why this matters to me
I spent years in production and logistics work before moving into software, and in that world the costly mistakes were rarely dramatic. They were quiet: a count that was off by one, a row that got skipped, a label matched to the wrong order. Python loops can have the same kind of quiet mistakes. enumerate keeps the numbering honest, zip keeps the pairing honest, and strict=True makes sure nothing gets dropped without me knowing.
If you still write for i in range(len(items)), try rewriting one loop with these. The code gets shorter, and more importantly, it gets harder to get wrong.