Python Practice › Exception Handling Programs › Program 4
Handle an index out of range
Write a Python program that reads a list item by index and handles invalid indexes.
Input
index 1 and 10 of ["a", "b", "c"]
Output
1 b 10 is out of range for 3 items
Approach
- Catch
IndexError.
Solution
items = ["a", "b", "c"]for i in [1, 10]: try: print(i, items[i]) except IndexError: print(i, "is out of range for", len(items), "items")Output
1 b 10 is out of range for 3 items
Learn the concept
New to this topic? Read the lesson, then come back.