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.
Install the Python SDK to identify and fix exceptions
What Causes IndexError
This error occurs when an attempt is made to access an item in a list at an index which is out of bounds. The range of a list in Python is [0, n-1], where
n is the number of elements in the list. When an attempt is made to access an item at an index outside this range, an
IndexError: list index out of range error is thrown.
Python IndexError Example
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)
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) IndexError: list index out of range
How to Fix IndexError in 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
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 for a list can help iterate over it until the item at its last index and helps avoid the error.
The above approach can be used in the earlier example to fix the error:
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. Sign Up Today!