Fixing 'IndexError: list index out of range' in Python

beginner🐍 Python2026-06-08| Python 3.x (Any OS: Windows, macOS, Linux)

Error Message

IndexError: list index out of range
#python#list#indexerror#debugging#coding-tips

Quick Fix: The TL;DR

An IndexError happens when you try to grab an item from a list using a position (index) that doesn't exist. Since Python starts counting at 0, the highest valid index is always one less than the list's total length.

# The safest fix: Check length before you touch the list
if len(user_ids) > 5:
    print(user_ids[5])
else:
    print("List is too short!")

Why Is This Happening?

Think of a list like a row of five lockers numbered 0 to 4. If you try to open locker number 5, you'll find it doesn't exist. Python reacts to this by stopping your program and throwing an IndexError.

Common Mistakes

  • The Off-By-One Error: You have 10 items and try to access index 10. Remember, the 10th item is actually at index 9.
  • Empty Lists: Your code expects data, but the list is []. Accessing my_list[0] here will always fail.
  • Looping Pitfalls: You are deleting items from a list while still looping through it. This changes the list's size mid-flight.
  • Negative Indexing Overboard: You use my_list[-5] on a list that only has 3 items.

How to Fix It

1. Switch to "Pythonic" Iteration

Manually managing index variables is a recipe for mistakes. If you just need the items, loop through the list directly. This approach is cleaner and impossible to break with an index error.

# Avoid manual counters
for i in range(len(prices) + 1): # This +1 will crash your code
    print(prices[i])

# Do this instead
for price in prices:
    print(price)

Need the index number too? Use enumerate() to get both the count and the item safely:

for index, price in enumerate(prices):
    print(f"Item {index} costs {price}")

2. Use Defensive Length Checks

When your index comes from an external source—like a user's input or a database—verify it before using it. A simple if statement prevents a total crash.

def get_user_by_rank(users, rank):
    index = rank - 1 # Convert 1st place to index 0
    if 0 <= index < len(users):
        return users[index]
    return "User not found"

3. Try the Slicing "Hack"

Python's slicing syntax is surprisingly forgiving. While my_list[10] might crash, my_list[10:11] will simply return an empty list if the index is missing. This is a great way to fetch data without constant if checks.

colors = ["red", "blue"]

# This crashes:
# top_color = colors[2]

# This returns an empty list instead of crashing:
result = colors[2:3]
final_color = result[0] if result else "default"

4. Handle the Exception

Sometimes it is easier to ask for forgiveness than permission. Wrap your code in a try...except block to catch the error and provide a fallback value.

try:
    latest_post = blog_posts[0]
except IndexError:
    latest_post = "No posts yet!"
    print("Warning: The blog post list was empty.")

Debugging the Crash

If your script fails inside a complex loop, print the list size and the index right before the line that crashes. This usually reveals exactly where the logic went wrong.

print(f"DEBUG: List has {len(data)} items. Trying to access index {i}.")
value = data[i]

Final Checklist

Before you ship your code, test it against these three scenarios:

  • The Empty List: Does your code survive a list with zero items?
  • The Single Item: Does it handle a list with exactly one element?
  • The Boundary: If the list has 100 items, does your code correctly stop at index 99?

Related Error Notes