Last modified: Jan 10, 2023 By Alexander Williams

How to solve IndexError list index out of range

IndexError list index out of range is one of the most popular errors in python. In this tutorial, I'll show you the reasons for this issue and how to solve it.

Let's get started.

Reasons for IndexError list index out of range

IndexError list index out of range appears when you attempt to retrieve an index that does not exist in a list.

For example:


my_list = ["Cat", "Dog", "Tiger"]

print(my_list[5])

Output:

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

As you know, a list starts at index 0. And, my_list has 3 items that mean:

"Cat" => index 0
"Dog" => index 1
"Tiger" => index 2

But in the above example, I want to get index 5 which does not exist in my_list. So, if you already know the number of items, you need just set the correct index.

Another example:


my_list = []

print(my_list[0])

Output:

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

In this example, we've attempted to get index 0 from the empty list. And therefore, we've got the error.

Solutions for IndexError list index out of range error

To solve IndexError list index out of range, you need to follow these solutions:

Solution 1: Check if the list is empty

If you want to retrieve the first or the last item, you need to check if the list is empty before using the index.


my_list = []

if my_list:
    print(my_list[0])
    
else:
    print("The list is empty!")

Output:

The list is empty!

For more details about this method, visit Python Check if Value Exists in List.

Solution 2: Compare between the number of items in the list and the index

"If the number of list items is bigger than the index, that means the index exists. Otherwise, the index doesn't exist."

Let's see an example:


my_list = ["Cat", "Dog", "Tiger"]

# index
my_index = 10

# Number of items
items_number = len(my_list)

if items_number > my_index:
    print(my_list[my_index])

else:
    print(f"index {my_index} doesn't exist")

Output:

index 10 doesn't exist

As you can see, we've used the len() function to get the number of items in my_list. Then, we've compared my_list and my_index.

Solution 3: Use try and except statement

The try and except statement is another solution to solve the error but, should be your last option.

Let's see how to use the statement:


my_list = ["Cat", "Dog", "Tiger"]

try:
    print(my_list[10])
except:
    print("Something wrong")

Output:

Something wrong