Pythondex
Python Programs

Handle Index Out Of Range Python Error

Last updated March 16, 2024 by Jarvis Silva

Looking for a way to handle index out of range python error then you are at the right place today I will share the python program to handle index error so follow till the end.

Index error or index out of range error is caused when you try to access a index in a list or a array which does not exists the compiler will throw error like below.


IndexError: list index out of range

So if someone try’s to access a index which does not exist the program will stop and exit so it is important to handle this error specially when dealing with user inputs because user can enter a index which does not exists which will stop program so now let’s see how to handle it.

Python Code To Handle Index Error


nums = [1, 2, 3]

try:
    print(nums[2])
except IndexError:
    print("Index out of range")

Above is the code for handling index out of range python exception, you can test this code on your computer or use this online python compiler it will print index out of range.

To handle this error I have used try and except statements. In the try statement it will try to execute the code if any error caused it will be caught in the except statement so it will not exit the program when error occurs.

I have specifically used except to catch IndexError only which catches index out of range error you can add this in your program where you want to handle IndexError.

Here are some more python tutorials for you:

  1. Handle divide by zero exception in python.
  2. Convert tiff to pdf in python programming.

I hope you found this tutorial helpful, Do share it with someone who might need it and join our telegram channel for free coding courses and future updates.

Thanks for reading, Have a nice day 🙂