How to fix IndexError: List index out of range?

How to fix IndexError: List index out of range?

When you’re working on a programming project, it’s easy to get stuck on some roadblocks. Sometimes, you just can’t figure out the problem, and no amount of Google searching seems to be helping. If you’re new to coding or Python in general, these types of issues can be even more frustrating.

When you’re learning how to code, it’s not uncommon to encounter errors like the IndexError: list index out of range. In this article, we’ll explain what that annoying error message means and how you can fix it—once and for all!

What is IndexError?

In order to understand IndexError, we need to understand how errors work in Python. There are two types of errors in Python, a Syntax Error and an Exception.

A syntax error is when the Python parser detects an incorrect statement. In our case, however, IndexError is an exception. An exception occurs when the program runs into an error even when the syntax is correct. There can be various types of exceptions depending on the kind of problem the program ran into, and IndexError is one of them.

Whenever your program runs into an exception, the output displays the type of exception it ran into (in our case, IndexError) followed by the error message. In our case, the error message is list index out of range which indicates the error occurred in a list. This exception occurs when we try to access an element in a list from an index that does not exist. Let us try to understand this with the help of an example.

Example

# Declaring list of cities cities = ['Kolkata', 'Mumbai', 'Bengaluru'] # Print the city at index 3 print(cities[3]);
Code language: Python (python)

Output

Traceback (most recent call last): File "main.py", line 4, in <module> print(cities[3]); IndexError: list index out of range
Code language: Bash (bash)

Here, we created a list named cities with 3 elements: Kolkata, Mumbai, and Bengaluru. Then we tried to print the element at the index 3 and got the above error: IndexError: list index out of range.

The reason for this is simple, the index of a list in Python and most other languages start from 0. So in the case of a list with 3 elements, the indexes of those elements will be 0, 1, and 2. As you can see, there’s no element at index 3 in the list we created. Hence, we got the error because we tried to access an index that does not exist in the list.

Solution

# Declaring list of cities cities = ['Kolkata', 'Mumbai', 'Bengaluru'] # Print the city at index 3 print(cities[2]);
Code language: Python (python)

Output

Bengaluru
Code language: Bash (bash)

As you can see from the correct example above, the solution is very straightforward. Here we are accessing index 2 from the list, which is the last index of the list. Hence, we are staying within the range of available indexes of the list we created (The range, in this case, being 0, 1, and 2). And voila! The error is gone, and the output is Bengaluru.

Example using loops

These errors are most common when looping through lists, as sometimes we put the wrong value in the range() function when using for loops. Let us see it in action.

# Declaring list of cities cities = ['Kolkata', 'Mumbai', 'Bengaluru', 'Delhi'] # looping through the list for i in range(0,5): # print the city at index i print(cities[i])
Code language: Python (python)

Output

Kolkata Mumbai Bengaluru Delhi Traceback (most recent call last): File "main.py", line 7, in <module> print(cities[i]) IndexError: list index out of range
Code language: Bash (bash)

We got the error again! You can also notice all 4 cities in the list were printed before we got the error; let us break this down.

The list cities has 4 elements; hence the indexes are 0, 1, 2, and 3.

The 2nd argument of the range() function is exclusive. This means for range(0, 5) the counting will start from 0 and end at 4. But the last available index on our list is 3. Hah, found the error! You can see we tried to access an index that does not exist in the list, which is why we got the same error again.

Solution

# Declaring list of cities cities = ['Kolkata', 'Mumbai', 'Bengaluru', 'Delhi'] # looping through the list for i in range(0,4): # print the city at index i print(cities[i])
Code language: Python (python)
Kolkata Mumbai Bengaluru Delhi
Code language: Bash (bash)

As you might have guessed, the correct range values, in this case, would be range(0, 4). The error is gone, and all the cities are printed!

Things to keep in mind

Here are a few things you can try when you come across an IndexError exception:

  • Double-check the range of indexes you are looping through.
  • If you are unsure, try printing the length of the list using the len() function.
  • Be careful about comparison operators in while loops (i <= 4 means 0 to 4, whereas i < 4 means 0 to 3).

Conclusion

Whenever you come across an error, the first thing you should try is googling it. There’s a chance that someone else has encountered the same issue when coding and already found the solution! Once you’ve made sure that the error isn’t caused by a problem with your computer, you can start trying to figure out what caused it and how to fix it. If you’re new to coding, these types of errors may initially seem really confusing. However, with a little practice and patience, you’ll be able to solve them quickly and easily!

Thank you for reading!

Sharing is caring

Did you like what Supantha Paul wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far