What is ‘List Index out of Range’

A simple list is a collection of multiple objects. In the world of computer science, a list is considered as a collection just like an array, stack, heap, queue, etc. that is used to store multiple instances of the same datatypes. For example, an integer list of size 5 will be capable of storing 5 different integers in it as shown in the image below:

An Integer List of Size 5

What is “List Index out of Range”?

In all programming languages, there are certain types of errors and exceptions that arise due to an invalid piece of code. “List Index out of Range” is also an exception, which occurs whenever the user tries to access an invalid index of the list. By an invalid index, we mean that the index does not come in the range of the list at the time of its declaration.

List Index out of Range Exception

Another point to be noted here is that the list indexes do not start from “1” rather their numbering starts from “0”. It means that a list of size “5” will have the following five indexes: “0”, “1”, “2”, “3”, and “4”. This implies that if you will try to actually access the fifth index of your list, then you will have to write List [4] instead of writing List [5] because the latter one is an invalid index.

Your operating system only allows you to access those indexes that are a part of the range of your list. If you will try to access anything beyond its range, then the “List Index out of Range” exception will be thrown. That is exactly why people do not write List [Length] whenever they want to access the last index of the list rather they write List [Length -1] because the index numbering starts from “0” whereas the Length() function returns the actual capacity of the list. You will be able to understand this exception in a better way by looking at the code below.

A Code Snippet and its Output to explain the “List Index out of Range” Exception:

int List [4] = {1, 2, 3, 4}; 

cout<<” The length of the given list is ”<<Length(List)<<endl; 

cout<<” The first element is ”<<List[0]<<endl; //printing the first element of the list

cout<<” The second element is ”<<List[1]<<endl; //printing the second element of the list

cout<<” The third element is ”<<List[2]<<endl; //printing the third element of the list

cout<<” The fourth element is ”<<List[3]<<endl; //printing the fourth element of the list

cout<<List[Length]<<endl; //trying to access List[4] which is in fact an invalid index


The length of the given list is 4

The first element is 1

The second element is 2

The third element is 3

The fourth element is 4

List Index out of Range!
A Sample Code to Illustrate the “List Index out of Range” Exception
Ayesha Sajid
Ayesha is a software developer by profession and is currently working as a lead developer with Code5.Programming Skills: Asp.net, C#, C/C++, Java, Golang, Android, UML, SQL and Html.