What Does Enumerate Do in Python?
So, what does enumerate do in Python? Simply put, it adds a
counter to an iterable and returns it as an enumerate object, which you can
loop over to get both the index and the item.
Basic Syntax of enumerate()
python
CopyEdit
enumerate(iterable, start=0)
- iterable:
A sequence like list, tuple, or string
- start
(optional): The starting index value (default is 0)
Why Use enumerate()?
Let’s look at a regular loop without enumerate:
python
CopyEdit
fruits = ["apple", "banana", "cherry"]
index = 0
for fruit in fruits:
print(index,
fruit)
index += 1
Using enumerate() simplifies this:
python
CopyEdit
for index, fruit in enumerate(fruits):
print(index,
fruit)
Cleaner and more readable—this is one reason Python
developers love it.
Changing the Start Index
You can start the counter from any number:
python
CopyEdit
for index, fruit in enumerate(fruits, start=1):
print(index,
fruit)
Output:
CopyEdit
1 apple
2 banana
3 cherry
Use Cases of enumerate()
1. Tracking Index in Loops
Great for debugging or when you need to reference both the
index and value.
python
CopyEdit
for idx, char in enumerate("hello"):
print(f"Character
{char} at index {idx}")
2. Looping Through a List with Conditions
python
CopyEdit
colors = ["red", "green", "blue"]
for i, color in enumerate(colors):
if color == "green":
print(f"'green'
found at index {i}")
3. Working with Nested Loops
python
CopyEdit
matrix = [[1, 2], [3, 4]]
for i, row in enumerate(matrix):
for j, val in enumerate(row):
print(f"matrix[{i}][{j}]
= {val}")
enumerate() vs range(len())
You might’ve used range(len(list)) to loop with indices.
Here’s why enumerate is better:
Using range(len()):
python
CopyEdit
for i in range(len(fruits)):
print(i,
fruits[i])
Using enumerate:
python
CopyEdit
for i, fruit in enumerate(fruits):
print(i, fruit)
✅ More readable
✅
Less error-prone
✅
More "Pythonic"
enumerate() with List Comprehension (Bonus Tip)
Though enumerate() isn't typically used in list
comprehensions, you can still make it work:
python
CopyEdit
indexed = [(i, val) for i, val in enumerate(['a', 'b', 'c'])]
print(indexed)
# Output: [(0, 'a'), (1, 'b'), (2, 'c')]
Final Thoughts
Understanding what does enumerate do in Python can level up your loop
logic, especially when writing clean, concise code. Whether you're tracking
indexes, debugging, or working with nested structures, enumerate() helps make
your code simpler and more Pythonic.
Comments
Post a Comment