0
0
PythonHow-ToBeginner · 3 min read

How to Iterate Over List with Index in Python

In Python, you can iterate over a list with its index using the enumerate() function inside a for loop. This gives you both the index and the item in each loop step.
📐

Syntax

The basic syntax to iterate over a list with index is:

  • for index, item in enumerate(your_list): — loops through the list.
  • index — the current position in the list, starting at 0 by default.
  • item — the value at that position.

You can also specify a different start number with enumerate(your_list, start=1) if you want indexes to begin at 1.

python
for index, item in enumerate(your_list):
    # use index and item here
💻

Example

This example shows how to print each item in a list with its index using enumerate(). The index starts at 0 by default.

python
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")
Output
Index 0: apple Index 1: banana Index 2: cherry
⚠️

Common Pitfalls

A common mistake is trying to get the index by calling list.index(item) inside the loop, which is inefficient and wrong if items repeat.

Also, using a simple for item in list loop does not give you the index.

python
fruits = ['apple', 'banana', 'apple']

# Wrong way: using list.index() inside loop
for fruit in fruits:
    print(f"Index {fruits.index(fruit)}: {fruit}")  # This will print wrong indexes for duplicates

# Right way: use enumerate()
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")
Output
Index 0: apple Index 1: banana Index 0: apple Index 0: apple Index 1: banana Index 2: apple
📊

Quick Reference

Remember these tips when iterating with index:

  • Use enumerate() to get index and value together.
  • By default, index starts at 0 but you can change it with start=.
  • Avoid using list.index() inside loops for indexes.

Key Takeaways

Use enumerate() to loop over a list with access to both index and item.
The index from enumerate() starts at 0 by default but can start at any number with start=.
Avoid using list.index() inside loops as it is inefficient and incorrect for duplicate items.
A simple for item in list loop does not provide the index.
Enumerate makes your code cleaner and easier to read when you need indexes.