IndexError: list index out of range and python
If you have a list with 53 items, the last one is thelist[52]
because indexing starts at 0.
From Real Python: Understanding the Python Traceback - IndexError
:
IndexError
The
IndexError
is raised when you attempt to retrieve an index from a sequence, like alist
or atuple
, and the index isn’t found in the sequence. The Python documentation defines when this exception is raised:Raised when a sequence subscript is out of range. (Source)
Here’s an example that raises the
IndexError
:
test = list(range(53))test[53]---------------------------------------------------------------------------IndexError Traceback (most recent call last)<ipython-input-6-7879607f7f36> in <module> 1 test = list(range(53))----> 2 test[53]IndexError: list index out of range
The error message line for an
IndexError
doesn’t give you great information. You can see that you have a sequence reference that isout of range
and what the type of the sequence is, alist
in this case. That information, combined with the rest of the traceback, is usually enough to help you quickly identify how to fix the issue.
Yes,
You are trying to access an element of the list that does not exist.
MyList = ["item1", "item2"]print MyList[0] # Will workprint MyList[1] # Will Workprint MyList[2] # Will crash.
Have you got an off-by-one error?
The way Python indexing works is that it starts at 0, so the first number of your list would be [0]. You would have to print[52], as the starting index is 0 and therefore line 53 is [52]
.
Subtract 1 from the value and you should be fine. :)