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…

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

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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » Solved – IndexError: list index out of range." Ariessa Norramli | Sciencx - Sunday March 7, 2021, https://www.scien.cx/2021/03/07/solved-indexerror-list-index-out-of-range/
HARVARD
Ariessa Norramli | Sciencx Sunday March 7, 2021 » Solved – IndexError: list index out of range., viewed ,<https://www.scien.cx/2021/03/07/solved-indexerror-list-index-out-of-range/>
VANCOUVER
Ariessa Norramli | Sciencx - » Solved – IndexError: list index out of range. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/03/07/solved-indexerror-list-index-out-of-range/
CHICAGO
" » Solved – IndexError: list index out of range." Ariessa Norramli | Sciencx - Accessed . https://www.scien.cx/2021/03/07/solved-indexerror-list-index-out-of-range/
IEEE
" » Solved – IndexError: list index out of range." Ariessa Norramli | Sciencx [Online]. Available: https://www.scien.cx/2021/03/07/solved-indexerror-list-index-out-of-range/. [Accessed: ]
rf:citation
» Solved – IndexError: list index out of range | Ariessa Norramli | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.