IndexError: list index out of range error occurs when you try to access an index in a list that is outside the valid range of indices. In Python, list indices start from 0, so if you try to access an index that is greater than or equal to the length of the list, you will encounter this error. It indicates that the index you are trying to access does not exist in the list.
There are a couple of different ways to avoid the
IndexError: List index out of range. Let’s explore them one by one in this concise article.
Check List Length Before Accessing Index
The main point here is simple and straightforward: before accessing an index in the list, check if the index is within the valid range of the list length.
my_list = ['a', 'b', 'c', 'd', 'e'] index = 5 if index < len(my_list): value = my_list[index] print(value) else: # Do something else print("Please choose a valid index")
Please choose a valid index
Use Try/Except Block
An alternative solution is to use a
try/except block to catch the
IndexError and handle it gracefully.
my_list = ['sling', 'academy', 'dot', 'com'] index = 4 try: value = my_list[index] print(value) except IndexError: print("The list has no element at index", index)
The list has no element at index 4