IndexError: List Index Out of Range

IndexError: list index out of range

Quick Answer

You are accessing an index that does not exist. The list is shorter than expected. Check length with len() before accessing by index.

Why This Happens

Python lists are zero-indexed, so a list of 3 elements has valid indices 0, 1, and 2. Accessing index 3 raises IndexError. This often occurs with off-by-one errors or empty lists.

The Problem

items = ['a', 'b', 'c']
print(items[3])

result = []
first = result[0]

The Fix

items = ['a', 'b', 'c']
if len(items) > 3:
    print(items[3])

result = []
first = result[0] if result else None

Step-by-Step Fix

  1. 1

    Check list length

    Print len(your_list) to verify element count.

  2. 2

    Handle empty lists

    Check if my_list: first = my_list[0].

  3. 3

    Use negative indices carefully

    list[-1] gets the last element but still fails on empty lists.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free