IndexError Exception in Python with Example

Here, we are going to learn about the IndexError Exception and Python program to demonstrate it.
Submitted by IncludeHelp, on March 14, 2021

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.

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.

Here is an 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.

Program to illustrate index error in Python

# Program to illustrate IndexError Exception in Python...

# Try Block Starts
    # 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:

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


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


In the above 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.

Python exception handling programs »


Comments and Discussions!


Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.