Python development provides multiple ways to track index value while iterating over a list. The most common and efficient is using enumerate(), you can also range(len()) for index-based access when needed.

Method 1: Using enumerate() (Recommended)

The enumerate() function adds a counter to your iterable and returns both the index and the value.

python

fruits = [‘apple’, ‘banana’, ‘cherry’]

for index, fruit in enumerate(fruits):

    print(index, fruit)

Output:

output

0 apple  1 banana  

2 cherry

Best for most use cases where index and item are needed together.

Method 2: Manual Counter with range(len())

You can manually loop using range() and access items by index, though it’s more verbose.

python

fruits = [‘apple’, ‘banana’, ‘cherry’]

for i in range(len(fruits)):

    print(i, fruits[i])

Output:

output

0 apple  1 banana  

2 cherry

Less readable and Pythonic, but useful when working with indexes only.

Also Read:

Tip

  • Use enumerate() when you need both index and value.
  • You can start counting from any number using enumerate(iterable, start=n).

python

for idx, item in enumerate(fruits, start=1):    print(idx, item)