Skip to content

How to Fix IndexError: list index out of range in Python

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about How to Fix IndexError: list index out of range in Python. We cover key concepts, practical examples, and best practices.

Python raises IndexError: list index out of range when you try to access an element at an index that exceeds the length of the sequence.

The Wrong Way

items = [10, 20, 30]
print(items[5])

This produces:

Traceback (most recent call last):
  File "script.py", line 2, in <module>
    print(items[5])
IndexError: list index out of range

The Right Way

Check the list length before accessing an index:

items = [10, 20, 30]
index = 5
if index < len(items):
    print(items[index])
else:
    print(f"Index {index} out of range")

Output:

Index 5 out of range

Step-by-Step Fix

1. Verify the sequence length

items = [10, 20, 30]
print(len(items))  # 3

Valid indices are 0 through len(items) - 1. Index 3 is out of range for a 3-element list.

2. Check loop boundaries

# Wrong
items = [10, 20, 30]
for i in range(len(items) + 1):  # goes up to index 3
    print(items[i])

# Right
for i in range(len(items)):
    print(items[i])

3. Use negative indexing safely

Negative indices wrap around but still have bounds:

items = [10, 20, 30]
print(items[-1])  # 30 -- last element
print(items[-4])  # IndexError -- only 3 elements

4. Use try-except for dynamic access

items = [10, 20, 30]
index = 10
try:
    print(items[index])
except IndexError:
    print(f"Index {index} is out of range for list of length {len(items)}")

Prevention Tips

  • Always check index < len(sequence) before direct access.
  • Use enumerate() when iterating with indices.
  • Use negative indices (-1, -2) to access from the end safely.
  • For pop operations, check if list: before calling .pop().
  • Use sequence[-1] to access the last element instead of sequence[len(sequence)-1].

Common Mistakes with indexerror

  1. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  2. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  3. Using return to exit a function early instead of wrapping a pure value in the monad

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why does Python use 0-based indexing?

Python follows C's convention of 0-based indexing where list[0] is the first element. This means valid indices range from 0 to len(list) - 1. Index len(list) is always out of range.

Does IndexError only happen with lists?

No. IndexError applies to any sequence type: lists, tuples, strings, and any object that implements __getitem__ with integer indices. "hello"[10] also raises IndexError.

How do I safely get the last element of a possibly-empty list?

Use list[-1] still raises IndexError if the list is empty. Instead, use list[-1] if list else default_value. The conditional checks for emptiness before accessing the index.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro