IndexError: list index out of range [Solved]

IndexError: list index out of range [Solved]

What is IndexError in Python?

In this tutorial, we will learn about how to fix error “IndexError: list index out of range”. In Python, the “IndexError” in general occurs whenever we try to access an index of a iterable(list, string and tuple) that does not exist. Iterables are zero-based wich means the first element is at index 0, second element is at index 1 and so on. So if you try to access an index beyond the range of iterable(i.e greater than or equal to length of an iterable), Python raises an error.

 

IndexError: list index out of range [Solved]

The “IndexError: list index out of range” error is very specific to List. So if you try to access an index in list that does not exist, Python will throw this error. In the upcoming section, we will cover four examples and show case how the same error is reported by Python for built-in modules List, Tuple and String.

 

Example-1: Error Occurs While Using Built-in Modules

In this example, we will write a Python program  to create a Calendar for a specific month, specific year. To do this, we will utilize Python’s built-in module known as Calendar. This module provides a function, month(). This function takes in two argument, year and month. Based on argument provided to month() function, it will create and return a calendar. But what if we provide a month beyond 12? what will happen? Let us see that in below code.

import calendar

year = 2023
month = 14

print(calendar.month(year, month))
OUTPUT
> python .\indexerror.py
Traceback (most recent call last):
File "D:\linuxnasa\indexerror.py", line 4, in <module>
print(calendar.month(year, month))
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\calendar.py", line 360, in formatmonth
s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\calendar.py", line 343, in formatmonthname
s = month_name[themonth]
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\calendar.py", line 61, in __getitem__
funcs = self._months[i]
IndexError: list index out of range

As you see the output above, index error has been thrown. This is because we have passed the month value as 13 which is invalid. Hence Python throws the error.

Error Fix:  To fix the Error , provide a valid month value i.e less than or equal to 12.

 

Example-2: Error Occurs While Using List

In this example, we will create a list which will hold three elements. We will iterate over the list and try to access the index which does not exist. Let’s see what happens.

nums = [1, 2, 3]

length = len(nums)
for i in range(1, length):
    print(nums[length +1 ])
OUTPUT
> python .\indexerror.py
Traceback (most recent call last):
File "D:\linuxnasa\indexerror.py", line 4, in <module>
print(nums[length +1 ])
IndexError: list index out of range

As you see the output above, Python has thrown the IndexError. This is because We are trying to access the index (length+1) which is equal to 4 but the actual size of list is three. Hence Python throws the error.

Error Fix: To resolve the error, access any index which is less than the length of list.

 

 

Example-3: Error Occurs While Using Tuple

In this example, we will create a tuple which will hold three elements. We will again try to access a index that does not really exist in the tuple. Let us execute the below code and see what happens.

nums = (10, 20, 30)

length = len(nums)
for i in range(1, length):
    print(nums[length + 2 ])
OUTPUT
> python .\indexerror.py
Traceback (most recent call last):
File "D:\linuxnasa\indexerror.py", line 4, in <module>
print(nums[length + 2 ])
IndexError: tuple index out of range

As you see the output above, even for tuple, Python has thrown IndexError. This is again because we are trying to access an index in tuple which is greater that the length of the tuple.

Error Fix: To fix the error, change the index value to any other integer value which is less than the length of the tuple.

 

Example-4: Error Occurs While Using String

In this example, we will perform the same operation as we did in all previous examples. This time we will create a variable that holds a string. We will then try to fetch the character in the string from the index which is beyond the length of the string. Let us execute below code.

nums = 'linuxnasa'

length = len(nums)
for i in range(1, length):
    print(nums[length +1 ])
OUTPUT
> python .\indexerror.py
Traceback (most recent call last):
File "D:\linuxnasa\indexerror.py", line 4, in <module>
print(nums[length +1 ])
IndexError: string index out of range

As you see the output above, same IndexError is thrown for string as well.

Error Fix: Try to access any character within the length of the string.

 

Summary

We have successfully resolved the IndexError for multiple iterable in Python. If you want to learn more about List capabilities in Python, refer to python.org official documentation.

Leave a Comment