Open In App

Python List Index Out of Range – How to Fix IndexError

Last Updated : 07 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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.

Example: Here our list is 3 and we are printing with size 4 so in this case, it will create a list index out of range.

Python3




j = [1, 2, 4]
print(j[4])


Output

    print(j[4])
          ~^^^
IndexError: list index out of range

Similarly, we can also get an Indexerror when using negative indices.

Python3




my_string = "Geeksforgeeks"
print(my_string[-61])


Output

    print(my_string[-61])
          ~~~~~~~~~^^^^^
IndexError: string index out of range

How to Fix IndexError in Python

  1. Check List Length: It’s important to check if an index is within the valid range of a list before accessing an element. To do so, you can use the function to determine the length of the list and make sure the index falls within the range of 0 to length-1.
  2. Use Conditional Statements: To handle potential errors, conditional statements like “if” or “else” blocks can be used. For example, an “if” statement can be used to verify if the index is valid before accessing the element.if or try-except blocks to handle the potential IndexError. For instance, you can use a if statement to check if the index is valid before accessing the element.

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads