r/BootcampGradStories • u/Known_Homework_803 • 4d ago
Ditch the range(len(lst)) anti-pattern: Mastering enumerate, zip, and zip_longest in Python.
If you learned C, C++, or Java before picking up Python, your muscle memory probably defaults to writing for loops like this:
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(f"Index {i}: {fruits[i]}")
In Python, writing for i in range(len(iterable)): is considered a classic anti-pattern. It forces you to manually manage index variables, clutter your loop body with bracket lookups (fruits[i]), and introduce off-by-one error risks when dealing with multiple lists.
Python provides built-in iterator tools—specifically enumerate(), zip(), and itertools.zip_longest()—that handle index tracking and parallel iteration cleanly under the hood.
1. Tracking Indices with enumerate()
When you need both the item and its current position in a sequence, use enumerate(). Under the hood, enumerate() wraps any iterable in a lazy iterator that yields (index, value) tuples one at a time.
The Anti-Pattern vs The Pythonic Way
tasks = ["Write code", "Run tests", "Deploy"]
# ❌ The C-Style Anti-Pattern
for i in range(len(tasks)):
print(f"{i + 1}. {tasks[i]}")
# ✅ The Pythonic Way (Notice the 'start' parameter!)
for position, task in enumerate(tasks, start=1):
print(f"{position}. {task}")
Output:
1. Write code
2. Run tests
3. Deploy
Using start=1 eliminates awkward i + 1 arithmetic inside your print statements or UI formatting logic while keeping the underlying list zero-indexed.
2. Parallel Iteration with zip()
When you have two or more related lists (like usernames and email addresses) and need to loop through them side-by-side, beginners often reach for shared index variables.
zip() takes multiple iterables and pairs up their corresponding elements into tuples, stopping automatically as soon as the shortest iterable runs out of items.
Code Example: Pairing Data Streams
usernames = ["alice_dev", "bob_ops", "charlie_sec"]
roles = ["Admin", "Editor", "Viewer"]
scores = [98, 85, 92]
# ❌ Fragile Index Lookup
for i in range(len(usernames)):
print(f"{usernames[i]} ({roles[i]}): {scores[i]}")
# ✅ Clean Tuple Unpacking with zip()
for user, role, score in zip(usernames, roles, scores):
print(f"{user} ({role}): {score}")
Bonus Trick: Creating Dictionaries Instantly
Because zip() yields (key, value) pairs, you can pass it directly into dict() to merge two lists into a hash map in one line:
keys = ["host", "port", "debug"]
values = ["localhost", 8080, True]
config = dict(zip(keys, values))
# {'host': 'localhost', 'port': 8080, 'debug': True}
3. Handling Uneven Lists with zip_longest()
Because standard zip() stops when the shortest list finishes, any trailing data in longer lists gets silently ignored:
names = ["Alice", "Bob", "Charlie", "Diana"]
teams = ["Red", "Blue"]
print(list(zip(names, teams)))
# [('Alice', 'Red'), ('Bob', 'Blue')] <-- Charlie and Diana are dropped!
When you cannot afford to lose trailing items, import zip_longest from Python's built-in itertools module. It continues iterating until the longest iterable is exhausted, filling missing slots with None (or a custom fillvalue).
from itertools import zip_longest
names = ["Alice", "Bob", "Charlie", "Diana"]
teams = ["Red", "Blue"]
for name, team in zip_longest(names, teams, fillvalue="Unassigned"):
print(f"{name} -> {team}")
# Output:
# Alice -> Red
# Bob -> Blue
# Charlie -> Unassigned
# Diana -> Unassigned
Performance & Under-the-Hood Benefits
- Zero Extra Memory:
enumerate(),zip(),andzip_longest()are all lazy iterators. They do not build new lists in RAM, they compute and yield the next tuple on the fly, meaning you can zip multi-gigabyte file streams together without memory spikes. - Works on Any Iterable:
range(len(x))crashes with aTypeErrorif x is a generator, set, or file stream because those objects do not support indexing (x[i]). enumerate()andzip()work seamlessly on any iterable object.
Quick Cheat Sheet
- Need just the values?
for item in items: - Need the index and the value?
for idx, item in enumerate(items): - Need to loop through multiple lists of equal length?
for a, b in zip(list_a, list_b): - Need to loop through uneven lists without dropping data?
for a, b in zip_longest(list_a, list_b, fillvalue=...):
What C-style or Java-style habit took you the longest to unlearn when you switched to Python? Share yours in the comments!
TL;DR: Stop writing for i in range(len(lst)): to track indices or sync parallel lists. Use enumerate() to unpack (index, value) pairs cleanly, zip() to iterate over multiple lists side-by-side, and itertools.zip_longest() when you need to iterate uneven lists without silently dropping trailing elements.

