NovaCodes is where I write for backend builders — no fluff, just Python that works.
Let’s start simple — with something many skip over: enumerate()
.
🔧 Why enumerate()
Matters
A lot of people still write this:
for i in range(len(mylist)):
print(i, mylist[I])
If mylist is a generator, this throws an error. If someone refactors mylist[i] to something unsafe, you get index bugs.
Now look at this:
mylist = [4, 6, 9, 'a', 'y']
for index, item in enumerate(mylist):
print(index, item)
Cleaner. Readable. No more range(len(...)). No more index mistakes. You get both the index and the value — safely.
🔍 Use Case: Tagging and Filtering Log Lines
You’re reading logs and want to print line numbers that contain "ERROR":
def find_errors(path):
with open(path) as f:
for lineno, line in enumerate(f, start=1):
if "ERROR" in line:
print(f"⚠️ Line {lineno}: {line.strip()}")
🧠 Why start=1? Because real line numbers don’t start at 0.
🧪 Use Case 2: Mapping with Index Tags
You need to label each item in a report:
items = ["Login", "Search", "Export", "Logout"]
for idx, action in enumerate(items, start=100):
print(f"Action #{idx}: {action}")
This is clean index tagging — perfect for log IDs, unique prefixes, or batch IDs.
💣 Hidden Bug Example (Without enumerate())
def process(items):
for i in range(len(items)):
if some_condition(items[i]):
modify(items[i+1]) # ← Off-by-one bug if i+1 goes out of range!
Refactor with enumerate():
def process(items):
for index, item in enumerate(items):
if some_condition(item):
if index + 1 < len(items):
modify(items[index + 1])
Now it’s safer, cleaner, and easier to test.
♻️ Reusable Pattern
Turn this into a utility function:
def print_indexed(iterable, label="Item", start=0):
for idx, val in enumerate(iterable, start=start):
print(f"{label} {idx}: {val}")
Used like this: print_indexed(["apple", "banana", "cherry"], label="Fruit", start=1)
🧰 Quick Tips
- enumerate(iterable, start=0) lets you control the index
- Works on any iterable: lists, files, generators, sockets
- Memory-safe — doesn’t consume the whole iterable at once
- Combine with zip() or filter() for powerful patterns
🛰️ Closing Thought
This isn’t just a prettier loop. enumerate() makes your code:
- Safer
- Clearer
- Less error-prone
- More backend-ready
💬 Let's Talk
I wrote this because enumerate()
is often skipped over — yet it solves real backend problems like log parsing, safe indexing, and clean loop structure.
If you’ve used enumerate()
in a clever or unusual way, drop it in the comments — I’d love to see more patterns.
Or if something here raised a question, ask. I respond.
Follow if you’re building Python for real use — not tutorial views.
NovaCodes | novacodes.substack.com (archive)
Top comments (0)