Python Error

Fix: IndexError: list index out of range

Exact message

IndexError: list index out of range

Quick answer

IndexError: list index out of range means you accessed an element at a position that does not exist. Lists are 0-indexed, so a list with 3 elements has valid indices 0, 1, and 2 — accessing index 3 or higher raises IndexError.

Why this error happens

When you write my_list[i], Python checks that 0 <= i < len(my_list). If i is equal to or greater than the list length (or negative beyond -len), it raises IndexError. The most common scenario is a loop that uses <= len(my_list) instead of < len(my_list), or an API that returned fewer items than expected.

Example: Wrong vs Right

Wrong

items = [10, 20, 30]
print(items[3])
# IndexError: list index out of range

Right

items = [10, 20, 30]

# Check before accessing
if len(items) > 3:
    print(items[3])

# Or use safe access with default
def safe_get(lst, i, default=None):
    return lst[i] if 0 <= i < len(lst) else default

# Or catch the exception
try:
    print(items[3])
except IndexError:
    print("not enough items")

How to fix it (step by step)

  1. Print len(your_list) right before the failing line to see the real size
  2. Check your loop bounds — range(len(lst)) is safer than manual indexing
  3. If the list comes from an API or file, verify the count first
  4. For 'last element' access, use my_list[-1] which is safe when the list is non-empty

Frequently asked questions

Does negative indexing ever raise IndexError?

Yes, if the index is too negative. On a 3-element list, my_list[-3] is valid (first item) but my_list[-4] raises IndexError.

How do I iterate safely?

Prefer for item in my_list instead of for i in range(len(my_list)): my_list[i]. This avoids the index entirely.

What about NumPy arrays?

NumPy raises the same IndexError but with extra context. Use arr.shape to confirm dimensions before indexing.

Related Python errors

Need a fix for a different error?

Use the free to paste any traceback and get an AI-suggested fix in seconds.

Want an AI with memory for your project?

MonsterX AI remembers your codebase across chats.