🔧 Error Fixes
· 1 min read
Last updated on

Python IndexError: List Index Out of Range — How to Fix It


IndexError: list index out of range

You’re trying to access an element at a position that doesn’t exist. Lists are zero-indexed, so a list with 3 items has indices 0, 1, 2 — not 3.

Fix 1: Check your index

fruits = ["apple", "banana", "cherry"]

# ❌ Index 3 doesn't exist (only 0, 1, 2)
print(fruits[3])  # IndexError!

# ✅ Last item is at index 2 (or use -1)
print(fruits[2])   # "cherry"
print(fruits[-1])  # "cherry"

Fix 2: Check the list length first

items = get_items()  # Might return empty list

# ❌ Crashes if list is empty
first = items[0]

# ✅ Check first
if items:
    first = items[0]

# ✅ Or use a default
first = items[0] if items else None

Fix 3: Off-by-one in loops

items = [10, 20, 30]

# ❌ range(len) goes 0, 1, 2, 3 — but 3 is out of range
for i in range(len(items) + 1):  # Bug: +1
    print(items[i])

# ✅ Just use range(len)
for i in range(len(items)):
    print(items[i])

# ✅ Even better — iterate directly
for item in items:
    print(item)

Fix 4: Modifying a list while iterating

items = [1, 2, 3, 4, 5]

# ❌ Removing items changes the length mid-loop
for i in range(len(items)):
    if items[i] % 2 == 0:
        items.pop(i)  # IndexError eventually!

# ✅ Use list comprehension
items = [x for x in items if x % 2 != 0]

# ✅ Or iterate in reverse
for i in range(len(items) - 1, -1, -1):
    if items[i] % 2 == 0:
        items.pop(i)

Fix 5: Empty result from split/API

# ❌ If the string doesn't contain a comma
data = "hello"
parts = data.split(",")
second = parts[1]  # IndexError! Only one element

# ✅ Check length
parts = data.split(",")
if len(parts) > 1:
    second = parts[1]
📘