error solved

Solved – IndexError: list index out of range


In this article, you will learn how to solve IndexError: list index out of range.

Let’s look at a code example that produces the same error.

a = [1, 2, 3, 4, 5]

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

How to Solve IndexError: list index out of range

In order to solve it, you can use calculate the maximal index that can be accessed by the list. You need to make sure that you only access the list element from index 0 until the maximal index.

a = [1, 2, 3, 4, 5]

# Maximal index
maxIndex = len(a) - 1;

print(maxIndex);
# 4

print(a[4])
# 5

Share on social media

//