Back to code sutra Archive
Loop Smarter: Getting the Item AND Its Position at the Same Time!
Tuesday, January 27, 2026The Problem
Ever been looping through a list and thought, 'Ugh, I need to know *which* item I'm on, not just the item itself!' It's frustrating to keep a separate counter just for that and remember to update it.
The Solution
Let's say you want to print your shopping list with numbers. Here's how beginners often start, and then the much slicker way using `enumerate()`.
**The 'Before' (manual counter):**
python
my_shopping_list = ["apples", "bread", "milk"]
item_number = 0 # We have to start our own counter
for item in my_shopping_list:
print(f"Item {item_number}: {item}")
item_number += 1 # And don't forget to increment it!
**The 'After' (using `enumerate()`):**
python
my_shopping_list = ["apples", "bread", "milk"] # Here's our list of items
# 'enumerate' is like magic! It gives us two things for each loop:
# 1. The 'index' (the item's position, starting from 0)
# 2. The 'item' itself (the value from the list)
for index, item in enumerate(my_shopping_list):
print(f"Item {index}: {item}") # Now we can easily use both!
PRO
Why This Rocks
This makes your loops much cleaner, less prone to 'off-by-one' errors (because Python handles the counting!), and easier to read because the intention is clearer – you want both the position and the item.