Free Online Code Editor
Loop with index using enumerate.
# Basic enumerate
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Start from different index
print("\nStarting from 1:")
for i, fruit in enumerate(fruits, 1):
print(f"{i}. {fruit}")
# Create list of tuples
indexed = list(enumerate(fruits))
print(f"\nAs list: {indexed}")
# With dictionary
colors = {"red": "#FF0000", "green": "#00FF00", "blue": "#0000FF"}
print("\nDictionary items:")
for i, (key, value) in enumerate(colors.items()):
print(f"{i}: {key} = {value}")
# Practical example
lines = ["First line", "Second line", "Third line"]
print("\nNumbered output:")
for num, line in enumerate(lines, 1):
print(f"Line {num}: {line}")enumerate() adds counter to iterable. Returns (index, item) tuples. Use start parameter to begin from different number.