Handle an index out of range

EasyException Handling Programs · 4 of 20

Write a Python program that reads a list item by index and handles invalid indexes.

Advertisement
Input
index 1 and 10 of ["a", "b", "c"]
Output
1 b
10 is out of range for 3 items

Approach

  1. Catch IndexError.

Solution

Python
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.

More exception handling programs

← All 20 Exception Handling Programs

Leave a Comment