Print Index and Value of List in Python

  • Post category:List

Printing the index and value of each element in a list can be achieved using the enumerate() function. Here are two examples:

Example 1:

fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits):
    print(f"Index: {index}, Value: {fruit}")

Output:

Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: orange

Example 2:

numbers = [1, 2, 3, 4, 5]
for index, number in enumerate(numbers):
    print(f"Index: {index}, Value: {number}")

Output:

Index: 0, Value: 1
Index: 1, Value: 2
Index: 2, Value: 3
Index: 3, Value: 4
Index: 4, Value: 5