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. 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

Output:

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!

BEST GUIDE: Find Out Windows Experience Index in Windows 10Open Source Vulnerability Index Containing 140,000 Vulnerabilities Launched by…Fix: Blue Screen due to APC Index MismatchHow to Find Xiaomi Rollback Index and Avoid ARB Bricks What is  List Index out of Range  - 3What is  List Index out of Range  - 81What is  List Index out of Range  - 28