The enumerate()
function adds an index to an iterable, making it easy to loop through items while keeping track of their positions. It’s great for loops, tracking positions, and working with lists efficiently.
Example
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 apple
1 banana
2 cherry
This helps avoid manually managing an index variable in loops.
Syntax
enumerate(iterable, start=0)
- iterable → The list, tuple, or string to loop through.
- start (optional) → The starting index (default is
0
).
1. Custom Starting Index
Change the index to start from a different number.
names = ["Alice", "Bob", "Charlie"]
for i, name in enumerate(names, start=1):
print(i, name)
Output:
1 Alice
2 Bob
3 Charlie
Useful when working with 1-based numbering (like in tables or rankings).
2. Using enumerate()
with a List of Tuples
Works great when looping through paired data.
students = [("Alice", 85), ("Bob", 90), ("Charlie", 78)]
for i, (name, score) in enumerate(students, start=1):
print(f"{i}. {name} - {score}")
Output:
1. Alice - 85
2. Bob - 90
3. Charlie - 78
Perfect for structured data like test scores or rankings.
3. Creating a Dictionary from enumerate()
Quickly convert a list into a dictionary with indexes as keys.
items = ["pen", "notebook", "eraser"]
indexed_items = dict(enumerate(items, start=1))
print(indexed_items)
Output:
{1: 'pen', 2: 'notebook', 3: 'eraser'}
Useful for mapping items with unique IDs.
4. Using enumerate()
to Modify Lists
Easily update a list while looping.
prices = [100, 200, 300]
for i, price in enum