Yes ✅ — enumerate() works perfectly with strings.
In Python, a string is an iterable of characters, and enumerate() works with any iterable.
🔹 Basic Example
text = "python"
for index, char in enumerate(text):
print(index, char)
Output
0 p
1 y
2 t
3 h
4 o
5 n
👉 enumerate() returns (index, value) pairs.
🔹 With a Custom Start Index
for i, ch in enumerate("data", start=1):
print(i, ch)
Output
1 d
2 a
3 t
4 a
🔹 Why enumerate() Is Better Than range(len())
❌ Old / less Pythonic:
s = "spark"
for i in range(len(s)):
print(i, s[i])
✅ Pythonic:
for i, ch in enumerate("spark"):
print(i, ch)
✔ Cleaner
✔ Safer
✔ Faster (no repeated indexing)
🔹 Real-World Use Cases with Strings
1️⃣ Find positions of a character
s = "banana"
for i, ch in enumerate(s):
if ch == "a":
print(i)
Output
1
3
5
2️⃣ Index-aware string validation
password = "pa$$w0rd"
for i, ch in enumerate(password):
if ch == "$":
print(f"Special char at position {i}")
3️⃣ Convert string to indexed dictionary
text = "abc"
indexed = {i: ch for i, ch in enumerate(text)}
print(indexed)
Output
{0: 'a', 1: 'b', 2: 'c'}
🔹 Important Conceptual Insight (Interview Gold ⭐)
enumerate(string)
is internally equivalent to:
((0, string[0]), (1, string[1]), ...)
⚠️ It does NOT modify the string
✔ It only reads characters (strings are immutable)
🔹 Common Mistake
s = "hello"
for i, ch in enumerate(s):
ch = ch.upper() # ❌ does NOT change s
Why?
👉 ch is just a temporary variable
👉 Strings are immutable
Correct way:
s = "".join(ch.upper() for ch in s)
🔹 Summary
| Feature | Works with String? |
|---|---|
enumerate() | ✅ Yes |
| Returns index + char | ✅ |
| Modifies string | ❌ No |
| Pythonic | ✅ Very |
If you want, next we can do:
enumerate()behind the scenes (iterator internals)- Tricky interview questions
enumerate()vszip()vsrange()- Performance discussion
Just say continue 🚀