How to Fix List Index Out of Range in Python

Let’s see some examples that showed how we may solve the error.

Python Fix List Index Out of Range using Range()

The range is used to give a specific range, and the Python range() function returns the sequence of the given number between the given range.

Python3




# code
names = ["blue," "red," "green"]
 
for name in range(len(names)):
    print(names[name])


Output

blue,red,green

Python Fix List Index Out of Range using Index()

Here we are going to create a list and then try to iterate the list using the constant values in for loops.

Python3




li = [1, 2, 3, 4, 5]
 
for i in range(6):
    print(li[i])


Output

1
2
3
4
5
IndexError: list index out of range

Reason for the error –  The length of the list is 5 and if we are an iterating list on 6 then it will generate the error.

Solving this error without using Python len() or constant Value: To solve this error we will take the index of the last value of the list and then add one then it will become the exact value of length.

Python3




li = [1, 2, 3, 4, 5]
 
for i in range(li.index(li[-1])+1):
    print(li[i])


Output

1
2
3
4
5

Python Fix List Index Out of Range using Try Except Block

If we expect that an index might be out of range, we can use a try-except block to handle the error gracefully.

Python3




my_list = [1, 2, 3]
try:
    print(my_list[3])
except IndexError:
    print("Index is out of range")


Output

Index is out of range



Python List Index Out of Range – How to Fix IndexError

In Python, the IndexError is a common exception that occurs when trying to access an element in a list, tuple, or any other sequence using an index that is outside the valid range of indices for that sequence. List Index Out of Range Occur in Python when an item from a list is tried to be accessed that is outside the range of the list. Before we proceed to fix the error, let’s discuss how indexing work in Python.

Similar Reads

What Causes an IndexError in Python

Accessing Non-Existent Index: When you attempt to access an index of a sequence (such as a list or a string) that is out of range, an Indexerror is raised. Sequences in Python are zero-indexed, which means that the first element’s index is 0, the second element’s index is 1, and so on. Empty List: If you try to access an element from an empty list, an Indexerror will be raised since there are no elements in the list to access....

How to Fix IndexError in Python

...

How to Fix List Index Out of Range in Python

...

Contact Us