How to Fix IndexError: List Index Out of Range in Python

How to Fix IndexError: List Index Out of Range in Python
Table of Contents

If you've landed here, there's a good chance Python just threw an IndexError: list index out of range at you. It's one of the most common Python errors, and fortunately, one of the easiest to fix once you understand what's going on.

This error means you tried to access a position in a list that doesn't exist. Python lists are zero-indexed, meaning the first element is at index 0, the second is at index 1, and so on. So a list with 4 elements has valid indices 0, 1, 2, and 3 — not 4.

A Quick Example

IndexError: list index out of range example illustration

test_list = [1, 2, 3, 4]
print(test_list[4])

There are 4 elements in test_list, so the valid indices are 0 through 3. Accessing index 4 is one past the end, which produces:

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

Common Causes

Before jumping to fixes, it helps to identify why the error is happening in your code. Here are the most frequent culprits:

  • Off-by-one errors in loops — Using <= instead of < when iterating, or starting a range at 1 instead of 0.
  • Hardcoded indices — Assuming a list has a certain number of elements (e.g., always accessing my_list[5]) when it sometimes doesn't.
  • Empty lists — Calling my_list[0] on a list that turned out to be empty, often because a function, query, or API returned no results.
  • Dynamic data — Working with user input, file contents, or database results where the list length can vary unpredictably.

How to Fix It

There's no single fix — the right approach depends on what your code is doing. Here are the most effective strategies.

1. Iterate Directly Over the List

If you're looping through a list just to access each element, you don't need indices at all. This is the most Pythonic approach and eliminates the possibility of an IndexError entirely:

test_list = [1, 2, 3, 4]

for item in test_list:
    print(item)
1
2
3
4

2. Use enumerate() When You Need the Index

If you need both the index and the value during iteration, enumerate() gives you both safely:

test_list = [1, 2, 3, 4]

for index, item in enumerate(test_list):
    print(f"Index {index}: {item}")
Index 0: 1
Index 1: 2
Index 2: 3
Index 3: 4

3. Use range(len()) for Index-Based Loops

If you specifically need to work with indices (for example, to modify elements in place), combine range() and len(). The range() function generates numbers from 0 up to but not including the value you pass, which means range(len(test_list)) produces exactly the valid indices:

test_list = [1, 2, 3, 4]

for i in range(len(test_list)):
    print(test_list[i])
1
2
3
4

4. Check the Length Before Accessing an Index

When you need to access a specific index and aren't sure the list is long enough, guard with a length check:

test_list = [1, 2, 3, 4]
index = 4

if index < len(test_list):
    print(test_list[index])
else:
    print(f"Index {index} is out of range for a list of length {len(test_list)}")

This is especially useful when working with dynamic data where list size isn't guaranteed.

5. Use Negative Indexing to Access the End

A common source of this error is trying to grab the last element with an incorrect index. Python supports negative indexing, where -1 is the last element, -2 is the second to last, and so on:

test_list = [1, 2, 3, 4]

print(test_list[-1])  # 4
print(test_list[-2])  # 3

This is much safer than calculating test_list[len(test_list) - 1] manually.

6. Handle the Error with Try/Except

When the list length is genuinely unpredictable — such as when parsing external data — you can catch the error and handle it gracefully:

test_list = [1, 2, 3, 4]

try:
    print(test_list[10])
except IndexError:
    print("That index doesn't exist in the list.")

Use this as a safety net rather than a primary strategy. If you can prevent the error with a length check or better loop logic, that's usually clearer.

Quick Reference

Cause Recommended Fix
Looping with wrong range Use for item in list or range(len(list))
Need index + value in loop Use enumerate()
Accessing a specific index Check if index < len(list) first
Grabbing the last element Use list[-1]
Empty list Check if list or if len(list) > 0 before access
Unpredictable data Wrap in try/except IndexError

Conclusion

The IndexError: list index out of range almost always comes down to one thing: your code assumes the list has more elements than it actually does. The fix is to make sure you're never reaching past the end. Whether that means iterating directly, checking lengths, or catching exceptions depends on your specific situation - but now you have all the tools to handle it.

Now that you know how to fix this error, the next step is making sure you catch it before your users do...

Track, Analyze and Manage Errors With Rollbar

Rollbar interface

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Install the Python SDK to identify and fix exceptions today!

Related Resources

Build with confidence. Release with clarity.

Rollbar helps you track what breaks, understand why, and improve what comes next.

5K free events per month, forever
14-day full feature trial
Easy and quick installation
Get started in minutes

Plans starting at $0. Take off with our 14-day full feature Free Trial.