This content originally appeared on CodeSource.io and was authored by Ariessa Norramli
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
The post Solved – IndexError: list index out of range appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Ariessa Norramli

Ariessa Norramli | Sciencx (2021-03-07T11:21:28+00:00) Solved – IndexError: list index out of range. Retrieved from https://www.scien.cx/2021/03/07/solved-indexerror-list-index-out-of-range/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.