Some text some message..
Back 🔷 What is enumerate() in Python? 23 Jun, 2025

The enumerate() function adds a counter/index to an iterable (like a list, tuple, or string) and returns it as an enumerate object.

It is mostly used in loops, especially for loops, when you need both index and value.


✅ Syntax

enumerate(iterable, start=0)
Parameter Description
iterable The sequence (list, tuple, etc.)
start The starting index (default is 0)

🔁 Basic Example

fruits = ['apple', 'banana', 'cherry']

for index, value in enumerate(fruits):
    print(index, value)

🟢 Output:

0 apple
1 banana
2 cherry

🔁 With Custom Start Index

for index, value in enumerate(fruits, start=1):
    print(index, value)

🟢 Output:

1 apple
2 banana
3 cherry

🎯 Use Case: Tracking Index While Iterating

Without enumerate():

for i in range(len(fruits)):
    print(i, fruits[i])

With enumerate() (simpler and cleaner):

for i, fruit in enumerate(fruits):
    print(i, fruit)

🧪 Convert to List or Tuple

enum_obj = enumerate(['a', 'b', 'c'])
print(list(enum_obj))  # Output: [(0, 'a'), (1, 'b'), (2, 'c')]

🔍 Loop Over String Using enumerate()

for i, char in enumerate("Python"):
    print(i, char)

🟢 Output:

0 P
1 y
2 t
3 h
4 o
5 n

💡 Best Practices

✅ Use enumerate() when you need both index and value
✅ Use the start= parameter to change base index
✅ Combine it with conditional logic for powerful loops


🧠 Real-World Use Case: Find First Match

names = ['Abhi', 'John', 'Ravi', 'John']

for i, name in enumerate(names):
    if name == 'John':
        print("First John found at index", i)
        break