Blog |

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

The IndexError: list index out of range error occurs in Python when an item from a list is attempted to be accessed that is outside the index range of the list. The range of a list in Python is [0, n-1], where n is the number of elements in the list.

Python IndexError Example

IndexError: list index out of range example illustration

Here’s an example of a Python IndexError: list index out of range thrown when trying to access an out of range list item:

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

In the above example, since the list test_list contains 4 elements, its last index is 3. Trying to access an element an index 4 throws an IndexError: list index out of range:

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

How to Fix IndexError in Python

The Python IndexError: list index out of range can be fixed by making sure any elements accessed in a list are within the index range of the list. This can be done by using the range() function along with the len() function.

The range() function returns a sequence of numbers starting from 0 ending at the integer passed as a parameter. The len() function returns the length of the parameter passed. Using these two methods together allows for safe iteration over the list up to its final element, thus ensuring that you stay within the valid index range and preventing the IndexError.

Here's how to use this approach to fix the error in the earlier example:

test_list = [1, 2, 3, 4]

for i in range(len(test_list)):
    print(test_list[i])

The above code runs successfully and produces the correct output as expected:

1
2
3
4

Track, Analyze and Manage Errors With Rollbar

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

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape