Python enumerate()
Function
The enumerate() function in Python is used to loop through a sequence (like a list, tuple, or string) while keeping track of the index of the current item.
It's a clean and Pythonic way to write loops when you need both index
and value
.
Syntax
enumerate(iterable, start=0)
Parameters:
iterable
– A sequence like a list, tuple, or stringstart
– The index to start counting from (default is 0)
Returns:
- An enumerate object which can be used in a loop to get
(index, value)
pairs
Basic Example
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
0 apple
1 banana
2 cherry
Example: Start Counting from 1
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
1 apple
2 banana
3 cherry
Use Case: Replacing Manual Counter in Loops
Instead of writing:
i = 0
for item in fruits:
print(i, item)
i += 1
You can simplify it using enumerate()
:
for i, item in enumerate(fruits):
print(i, item)
Use Case: Working with Strings
for i, char in enumerate("hello"):
print(f"Index {i} has character '{char}'")
Index 0 has character 'h'
Index 1 has character 'e'
Index 2 has character 'l'
Index 3 has character 'l'
Index 4 has character 'o'
Common Mistake
- Beginners often forget to unpack both
index
andvalue
fromenumerate()
. Always use:for i, val in enumerate(...)
Interview Tip
enumerate()
is often preferred in interviews over manually tracking counters in loops. It shows clean, Pythonic style.
Summary
enumerate()
helps track both index and item while looping.- You can change the starting index using the
start
argument. - Useful for iterating through lists, strings, or any iterable.
Practice Problem
Write a program that takes a list of names and prints them numbered from 1:
names = ["Alice", "Bob", "Charlie"]
for i, name in enumerate(names, start=1):
print(f"{i}. {name}")
Expected Output:
1. Alice
2. Bob
3. Charlie