enumerate

# Define a list of items
items = ["apple", "banana", "cherry"]

# Use enumerate to iterate with the index
for index, item in enumerate(items):
    print(f"Index: {index}, Item: {item}")
Index: 0, Item: apple
Index: 1, Item: banana
Index: 2, Item: cherry
# Define a list of items
items = ["apple", "banana", "cherry"]

# Use enumerate to iterate with the index starting at 1
for index, item in enumerate(items, start=1):
    print(f"Index: {index}, Item: {item}")
Index: 1, Item: apple
Index: 2, Item: banana
Index: 3, Item: cherry
# Define a tuple of items
items = ("apple", "banana", "cherry")

# Use enumerate to iterate with the index
for index, item in enumerate(items):
    print(f"Index: {index}, Item: {item}")
Index: 0, Item: apple
Index: 1, Item: banana
Index: 2, Item: cherry
# Define a string
text = "hello"

# Use enumerate to iterate with the index
for index, char in enumerate(text):
    print(f"Index: {index}, Character: {char}")
Index: 0, Character: h
Index: 1, Character: e
Index: 2, Character: l
Index: 3, Character: l
Index: 4, Character: o
# Define a list of items
items = ["apple", "banana", "cherry"]

# Use enumerate in a list comprehension to create a list of indexed items
indexed_items = [f"{index}: {item}" for index, item in enumerate(items)]
print(indexed_items)
['0: apple', '1: banana', '2: cherry']
# Define a dictionary
fruit_colors = {"apple": "red", "banana": "yellow", "cherry": "red"}

# Use enumerate to iterate over dictionary keys with an index
for index, key in enumerate(fruit_colors.keys()):
    print(f"Index: {index}, Key: {key}")
Index: 0, Key: apple
Index: 1, Key: banana
Index: 2, Key: cherry
# Define a dictionary
fruit_colors = {"apple": "red", "banana": "yellow", "cherry": "red"}

# Use enumerate to iterate over dictionary values with an index
for index, value in enumerate(fruit_colors.values()):
    print(f"Index: {index}, Value: {value}")
Index: 0, Value: red
Index: 1, Value: yellow
Index: 2, Value: red
# Define a list of lists
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Use enumerate in nested loops to iterate with row and column indices
for row_index, row in enumerate(matrix):
    for col_index, value in enumerate(row):
        print(f"Row: {row_index}, Col: {col_index}, Value: {value}")
Row: 0, Col: 0, Value: 1
Row: 0, Col: 1, Value: 2
Row: 0, Col: 2, Value: 3
Row: 1, Col: 0, Value: 4
Row: 1, Col: 1, Value: 5
Row: 1, Col: 2, Value: 6
Row: 2, Col: 0, Value: 7
Row: 2, Col: 1, Value: 8
Row: 2, Col: 2, Value: 9
# Define a function that processes index-value pairs
def process_items(index_item_pairs):
    for index, item in index_item_pairs:
        print(f"Processing item {item} at index {index}")

# Define a list of items
items = ["apple", "banana", "cherry"]

# Pass enumerate to the function
process_items(enumerate(items))
Processing item apple at index 0
Processing item banana at index 1
Processing item cherry at index 2