IndexError in Python

IndexError is raised when an element in a python collection like list,tuple is accessed with an invalid index.IndexError is an exception raised at runtime.

Collection Updated 30 Sep 2016 1 min read

Error Name

IndexError

ErrorText

List index out of range

Type of Error

IndexError is a python exception raised during the run time of a python program.

When IndexError is raised?

In any python collection like list, tuple, dictionary
the elements of the collection are accessed using the subscript operator [] and an index.
In python indexes are zero based. The first element in a collection is addressed using
collection[0], second element as collection[1] and so on till collection[count-1].

When the indexes that are out of the range is specified, that is an index that is not in the
range of 0 to count-1, than the error ErrorText: List index out of range error is raised.

Example:

python
SimpleList = [10,20,30]

print(SimpleList[2]) # This statement will be executed

print(SimpleList[3]) # Will raise an IndexError

Output

Output
30

Traceback (most recent call last):

  File "Error.py", line 3, in <module>

    print(SimpleList[3]) # Will raise an IndexError

IndexError: list index out of range

In this example the output of SimpleList[2]is printed as 30 without any error. That means the program has proceeded half way and has encountered a runtime error that is an exception of type IndexError