
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Catch IndexError Exception in Python
In Python, an IndexError occurs when you try to access a position (index) in a list, tuple, or similar collection that isn't there (does not exist). It means your program is trying to access the elements that are not available in the sequence (object).
Using try-except to Catch IndexError
You can use a try-except block to catch (handle) an IndexError and stop your program from crashing if you try to access an index that doesn't exist (or invalid).
Example
In this example, we try to access the 5th index of a list that only has 3 elements, which causes an IndexError -
my_list = [10, 20, 30] try: print(my_list[5]) except IndexError: print("IndexError caught: list index out of range.")
The output will be -
IndexError caught: list index out of range.
Catching IndexError Exception object
You can catch the exception object to access the specific error message provided by Python when an IndexError occurs.
Example
In this example, we are accessing an invalid tuple index and printing the exception message -
my_tuple = (1, 2, 3) try: print(my_tuple[10]) except IndexError as e: print("Caught IndexError:", e)
The output will be -
Caught IndexError: tuple index out of range
IndexError in Nested Structures
IndexError is also generated in case of nested data structures like lists of lists when accessing indexes that don't exist at a certain level.
Example
In this example, we try to access a sublist index that doesn't exist in the list, which will cause an error -
matrix = [[1, 2], [3, 4]] try: print(matrix[2][0]) except IndexError: print("IndexError caught in nested list.")
The output is -
IndexError caught in nested list.
How to Prevent IndexError Using Index Checks
You can prevent/avoid IndexError by checking the length of a list or tuple before accessing its elements.
Example
In this example, we are using a condition to ensure the index is within range before accessing the list -
data = [5, 6, 7] index = 4 if index < len(data): print(data[index]) else: print("Index is out of bounds.")
The output is -
Index is out of bounds.