Python IndexError Exception with Examples

Python | IndexError Exception: In this tutorial, we will learn about the IndexError Exception in Python with the help of examples. By IncludeHelp Last updated : June 20, 2023

Exception Handling in Python is the method using which exceptions are handled in python. Exceptions are errors that change the normal flow of a program.

Python programming language provides programmers a huge number of exception handler libraries that help them to handle different types of exceptions.

One such exception is the IndexError exception, let's understand it in detail.

Python IndexError Exception

IndexError Exception in Python is thrown when the passed value is not in the range of the given sequence [inputted value is out of range exception]. If it is not integer simply TypeError is thrown.

Example 1: Demonstrate the IndexError Exception

In this example, we have a Python list, and we're removing the elements using the list.pop() method. If the specified index does not exist in the list then the method will return an IndexError exception.

# declaring the list
x = [10, 20, 30, 40, 50, 60, 70]

# printing the list
print("x before pop operations...")
print("x: ", x)

res = x.pop(15) # will return an error
print(res," is removed")

# printing the list
print("x after pop operations...")
print("x: ", x)

Output

x before pop operations...
x:  [10, 20, 30, 40, 50, 60, 70]
Traceback (most recent call last):
  File "/home/main.py", line 8, in <module>
    res = x.pop(15) # will return an error
IndexError: pop index out of range

Example 2: Demonstrate the IndexError Exception with Try Except

Here is another example that will help you to learn more about it, suppose you have a list of names of 10 students in a class. And the user entered the input for the 12th student. This throws an IndexError.

In the below code, we have created a list consisting of the names of 5 employees of a company. And then prompted the user to enter the id of the employee to be searched. If the ID is out of the range of list, IndexError exception is thrown otherwise the ID is printed.

# Program to illustrate IndexError Exception in Python...

# Try Block Starts
try:
    # List to store employee name 
   employees = ["pankaj","amit","dilip","pooja","nitisha"]

   id = int(input("Enter Id (1-5):"))
   print("Your name is ",employees[id-1]," and your id is ",id)

# Value error if the values is not in range 
except ValueError as ex:
    print(ex)

# IndexError if the value is out of the list index...
except IndexError as ex:
    print(ex)

Output

Run 1: 
Enter Id (1-5):3
Your name is  dilip  and your id is  3

Run 2: 
Enter Id (1-5):59
list index out of range

Python exception handling programs »




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.