Python List Index Out Of Range: Error and Resolution

Hello coders!! In this article, we will learn about python list index out of range error and will also learn how to resolve such errors. At first, we should understand what does this means?

Python list index out of range arises when we try to access an invalid index in our Python list. In Python, lists can be initialized without mentioning the length of the list. This feature allows the users to add as much data to the list without encountering errors. But when accessing the data, you have to keep track of its index.

If you try to access the list index out of its range, it’ll throw an IndexError. Now, let us look into this topic deeply to have a better understanding.

What is IndexError Python List Index Out Of Range?

IndexError occurs when there is an invalid index passed to access the elements of the object. In python, the index starts from 0 and ranges till the length-1 of the list. Whenever the element is accessed from the list by using the square brackets, the __getitem__ method is called. This method first checks if the index is valid. The index cannot be float, or greater than or equal to the length of the list.

So, whenever you try to access the element which is not acceptable, IndexError is thrown. In our case, the index is out of the range, which means it’s greater than or equal to the length of the list. This error also applies to the indexing greater than the length of the string.

Causes of IndexError Python List Index Out Of Range?

There are several causes for this error to appear. Most of the causes are raised because the programmers assume that the list index starts from 1.

In Python, the list index begins from 0. Unfortunately, programmers who come from Lua, Julia, Fortran, or Matlab, are used to index the items from 1. In such cases, this error occurs.

There are many other scenarios where this error is raised, following are the examples of it –

Example 1: Python list index out of range with len()

color = ['red', 'blue', 'green', 'pink']
print(color[len(color)])

Output:

Python List Index Out Of Range With Len()
Output

Explanation:

In this code snippet, we have created a list called color having four elements – red, blue, green, pink

In python, the indexing of the elements in a list starts from 0. So, the corresponding index of the elements are:

  • red – 0
  • blue – 1
  • green – 2
  • pink – 3

The length of the list is 4. So, when we try to access color[len(color)], we are accessing the element color[4], which does not exist and goes beyond the range of the list. As a result, the list index out of bounds error is displayed.

Example 2: Python list index out of range in loop

def check(x):
    for i in x:
        print (x[i])

lst = [1,2,3,4]
check(lst)

Output:

Python List Index Out Of Range In Loop
Output

Explanation:

Here, the list lst contains the value 1,2,3,4 having index 0,1,2,3 respectively.

When the loop iterates, the value of i is equal to the element and not its index.

So, when the value of i is 1( i.e. the first element), it displays the value x[1] which is 2 and so on.

But when the value of i becomes 4, it tries to access the index 4, i.e. x[4], which becomes out of bound, thus displaying the error message.

Example 3: Case where your list length changes

lst=[1, 2, 3, 4, 4, 6]
for i in range(0,len(lst)):
    if lst[i]==4:
        lst.pop(i)

Output:

IndexError: list index out of range

Explanation:

In the above example, the user wants to remove the element if it matches a certain value. But the problem, in this case, is that while iterating, the length of your list is changing. So, when you reach the 6th iteration, the lst[6]==4 will throw an error because there is no 6th element in the list. When the two elements (4s) are removed the length of the list is reduced.

Solution for IndexError python list index out of range Error

The best way to avoid this problem is to use the len(list)-1 format to limit the indexation limits. This way you can not only avoid the indexing problems but also make your program more dynamic.

1. Lists are indexed from zero:

We need to remember that indexing in a python list starts from 0 and not 1. So, if we want to access the last element of a list, the statement should be written as lst[len-1] and not lst[len], where len is the number of elements present in the list.

So, the first example can be corrected as follows:

color = ['red', 'blue', 'green', 'pink']
print(color[len(color)-1])

Output:

Lists Are Indexed From Zero
Output

Explanation:

Now that we have used color[len(color)-1], it accesses the element color[3], which is the last element of the list. So, the output is displayed without any error.

2. Use range() in loop:

When one is iterating through a list of numbers, then range() must be used to access the elements’ index. We one forgets to use it, instead of index, the element itself is accessed, which may give a list index out of range error.

So, in order to resolve the error of the second example, we have to do the following code:

def check(x):
    for i in range(0, len(x)):
        print (x[i])

lst = [1,2,3,4]
check(lst)

Output:

Use Range() In Loop
Output

Explanation:

Now, that we have used the range() function from 0 to the length of the list, instead of directly accessing the elements of the list, we access the index of the list, thus avoiding any sort of error.

3. Avoiding pop() while iterating through the list

Code:

lst=[1, 2, 3, 4, 4, 6]
lst = [x for x in lst if x != 4]
print(lst)

Output:

[1, 2, 3, 6]

Explanation:

You can use the pop() function in a loop to remove the items from the list, but if you use the same list to change and iterate it’ll through an error. As an alternative to this, you can use the list comprehension along with an inline if to avoid adding elements to the list.

4. Avoiding remove() while iterating through the list

Code:

lst=[1, 2, 3, 4, 4, 6]
for i in range(len(lst)):
    if lst[i] == 4:
        lst.remove(4) # error
        print(lst)

# correct way
for i in range(lst.count(4)):
    lst.remove(4)

print(lst)

Output:

[1, 2, 3, 6]

Explanation:

In the above code, the user intends to remove all the occurrences of 4 from the list. But while iterating through the loop, the remove() function reduces its length. This causes an indexation error in lst[i]. As an alternative, you can use the range() function to use the remove() function a limited number of times. The count() function is amazingly helpful to avoid tedious loop errors.

5. Properly using While Loop

Code:

lst=[1, 2, 3, 4, 4, 6]
index = 0
while index < len(lst):
    print(lst[index])
    index += 1

Output:

1
2
3
4
4
6

Explanation:

Iterating through a while loop can be tricky sometimes. We first have declared the list with random elements and a variable with an integer value of 0. This is because the indexing starts from 0 in Python.

In the condition for the while loop, we’ve stated that the value of the index should be always less than the length of the list. Then we increment the value of the index by 1 in every loop. This creates perfect sync between the 0 and maximum value of the index to avoid any IndexErrors.

6+. Properly using For Loop

Code:

lst=[1, 2, 3, 4, 4, 6]
for i in range(len(lst)):
    print(lst[i])

Output:

1
2
3
4
4
6

Explanation:

Creating a proper for loop is an easy task, especially in python. Use the range() function to iterate the value from 0 to length-1 and close the loop thereafter.

Python List Index Out of Range Try Except

Exceptions are a great way of knowing what error you encounter in the program. Moreover, you can use the try-except blocks to avoid these errors explicitly. The following example will help you to understand –

Code:

lst=[1, 2, 3, 4, 4, 6]
try:
    for i in range(0,len(lst)+1):
        print(lst[i])
except IndexError:
    print("Index error reached")

Output:

1
2
3
4
4
6
Index error reached

Explanation:

In the above example, the value of ‘i’ ranges from 0 to the length of the list. At the very end of its value, it’ll throw IndexError because the index exceeds the maximum value. As a result, we’ve placed it inside the try block to make sure that we can handle the exception. Then we created an except block which prints whenever an exception is raised. The output can help you understand that the code breaks at its last iteration.

Need a Default Value instead of List Index Out of Range?

Sometimes, we need to initialize variables in such a way that, if an error is raised it’ll get assigned to the default value. This declaration can be achieved by using a try-except block or if statement. The following code will help you understand –

Code:

lst = [1, 2]

# case 1
try:
    value = lst[3]
except IndexError:
    value = "Some default value"

print(value)

# case 2
value = lst[3] if len(lst) > 3 else 'Some default value'

print(value)

Output:

Some default value
Some default value

Explanation:

Case 1, uses the try-except IndexError block to declare the value. As we have used [3] in the index and the length of the list is 2, it’ll execute the except block.

Case 2 uses a simple inline if statement which declares the value if the index is greater than the length of the list.

Must Read:

Python List Length | How to Find the Length of List in Python
How to use Python find() | Python find() String Method
Python next() Function | Iterate Over in Python Using next

Conclusion: Python List Index Out of Range

In day to day programming, list index out of range error is very common. We must make sure that we stay within the range of our list in order to avoid this problem. To avoid it we must check the length of the list and code accordingly.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Abdeljalil danane
Abdeljalil danane
2 years ago

Thank you very helpful