enumerate(): Loop with Index, The Pythonic Way! ✨If you ever need to loop through a list and get both the item and its index? Stop using
range(len())!👉 Python's
enumerate() function gives you a clean, efficient, and Pythonic way to do exactly that.my_fruits = ["apple", "banana", "cherry"]
# ❌ The Clumsy Way (Avoid!)
# for i in range(len(my_fruits)):
# print(f"Fruit {i}: {my_fruits[i]}")
# ✅ The Pythonic Way: enumerate()
for index, fruit in enumerate(my_fruits):
print(f"Fruit {index}: {fruit}")
Output:
Fruit 0: apple
Fruit 1: banana
Fruit 2: cherry
🎯 Always use
enumerate() when you need an index alongside your iterable items. It's cleaner, safer, and makes your loops shine!