What it does
enumerate() adds a counter to an iterable, so you get both the index (position) and the value when looping. It's cleaner than using range(len()).
Basic usage
items = ['apple', 'banana', 'cherry']
# Without enumerate (clumsy):
for i in range(len(items)):
print(i, items[i])
# With enumerate (clean):
for i, item in enumerate(items):
print(i, item)
# Output:
# 0 apple
# 1 banana
# 2 cherry
Start from different number
By default, enumerate starts at 0. You can change the start value:
items = ['apple', 'banana', 'cherry']
for i, item in enumerate(items, start=1):
print(f"{i}. {item}")
# Output:
# 1. apple
# 2. banana
# 3. cherry
When to use it
- You need both the index and value in a loop
- Displaying numbered lists or menus
- Modifying items based on their position
- Tracking position while iterating
Real example
students = ['Alice', 'Bob', 'Charlie']
print("Student list:")
for number, name in enumerate(students, start=1):
print(f"{number}. {name}")
# Output:
# Student list:
# 1. Alice
# 2. Bob
# 3. Charlie