AW Dev Rethought

✂️ Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away - Antoine de Saint-Exupéry

🐍 Python Everyday — ✨ enumerate: Stop Managing Loop Counters


Description:

When a loop needs both a position and a value, a hand-written counter adds work. enumerate() keeps them together.


Before: maintain a counter

tasks = ["Read", "Code", "Test"]
index = 0
for task in tasks:
    print(index, task)
    index += 1

This works, but you must initialize and update the counter yourself.


After: unpack the pair

for index, task in enumerate(tasks):
    print(index, task)
0 Read
1 Code
2 Test

Each iteration supplies a (count, value) pair. The loop unpacks that pair into index and task. For this unchanged list, iterated from its beginning with the default start=0, the count matches its index.


Number a checklist from one

for number, task in enumerate(tasks, start=1):
    print(f"{number}. {task}")
1. Read
2. Code
3. Test

start changes the initial count, not the iterable or its order. It does not skip the first item.


A display number is not a list index

The first checklist label is 1, but the first list item is still tasks[0].

print(tasks[0])  # Read

Use task directly in the loop. Using tasks[number] with start=1 would select the wrong items and eventually raise IndexError here. More generally, enumerate counts the iteration it receives; a filtered or sliced iterable does not automatically retain original source positions.


More than lists

Strings, tuples, generators and other iterables work too:

for position, letter in enumerate("PY"):
    print(position, letter)
# 0 P
# 1 Y

enumerate() is an iterator. It produces pairs as you advance it, without pre-building a list of all pairs. Once exhausted, that enumerate object stays exhausted; create a fresh one for another pass over a reusable source. A consumed generator source also needs to be recreated. Calling list(enumerate(...)) explicitly materializes the pairs.

If you only need values, keep it simple:

for task in tasks:
    print(task)

Takeaway: use enumerate() when you need a count and a value together. Choose start for the labels you want, and keep labels distinct from list indexes. This is a readability improvement, not a claim of measured speed gains.


Code Snippet:

# 1. The manual version: correct, but extra bookkeeping.
tasks = ["Read", "Code", "Test"]
print("Manual counter:")
index = 0
for task in tasks:
    print(index, task)
    index += 1

# 2. enumerate() supplies (count, value); the loop unpacks each pair.
# The default count starts at 0. No imports are needed.
print("Enumerate:")
for index, task in enumerate(tasks):
    print(index, task)

# 3. Start at 1 for human-facing labels, such as checklist numbers.
print("Checklist:")
for number, task in enumerate(tasks, start=1):
    print(f"{number}. {task}")

# 4. start changes the count, NOT the list's zero-based indexing.
print("First list item:", tasks[0])
# Use task directly above. tasks[number] would select the wrong item
# and eventually raise IndexError in this example.

# 5. Other iterables work too. Here we enumerate a string.
print("String:")
for position, letter in enumerate("PY"):
    print(position, letter)

# 6. An enumerate object is an iterator: it is consumed as you advance it.
# list() is used ONLY here to display the remaining pairs for illustration.
pairs = enumerate(tasks)
print("First pair:", next(pairs))
print("Remaining pairs:", list(pairs))
print("After exhaustion:", list(pairs))
# Make a fresh enumerate(tasks) to start a new pass over this list.

Link copied!

Comments

Add Your Comment

Comment Added!