The IndexError exception is raised when a sequence is subscripted with an index that is out of range. This usually happens when attempting to access a sequence such as a  list or tuple with an index that is greater than or equal to the length of the sequence. 

L = ["Python", "Pynerds"] 

print(L[0])
print(L[1])
print(L[2])

In the above case, the IndexError exception is raised because we tried to access the third item in the list while the list contains only two elements.

Avoiding and handling IndexError exceptions

The IndexError exceptions are especially common with beginners because it is easy to forget that indexing in Python begins at 0. So keeping this in mind is the first step to avoid the IndexError.

In cases where you are accessing items in a sequence dynamically, you can use the conditional blocks (if, elif, else) to ensure that the given index are within the required range.

T = (1, 2, 3, 4, 5, 6,7, 8, 9)

index = 10

if index <= 9:
    element = T[index]
    print("Element at index {} is {}".format(index, element))
else:
    print("Index should be smaller.")

You can also catch the IndexError exceptions using the try-except block. As shown below:

T = (1, 2, 3, 4, 5, 6,7, 8, 9)

index = 10

try:
    element = T[index]
    print("Element at index {} is {}".format(index, element))

except IndexError:
    print("Index should be smaller.")