You may sometimes get an IndexError such as the following when running your code:
IndexError: list index out of range
An IndexError means that your code is trying to access an index that is invalid. This is usually because the index goes out of bounds by being too large.
For example, if you have a list with three items and you try to access the fourth item, you will get an IndexError.
This can happen with strings, tuples, lists, and generally any object that is indexable.
Typically, Python will tell you which line is causing the error. For example:
Traceback (most recent call last): File "/tmp/pyrunnerj1Bs76Cx/code.py", line 3, in print(xs) IndexError: list index out of range
It can be helpful to read the error message carefully, paying special attention to the highlighted line.
Typically the cause of an IndexError is that you forgot that indexing starts at 0 in Python.
So if you have a list with two items:
letters = ["A", "B"]
letters is the first item,
letters is the last item, and
letters goes out of bounds and causes an IndexError
It can be useful to add in a call to
Try our practical beginner lessons, or test your skills with our challenges.