Handling Index Errors

Write a Python function that takes a list of numbers and an index as inputs, and returns the number at that index. If an index error occurs, return the string “Error: Index out of bounds”.

Example 1:

Input: [1, 2, 3, 4, 5], 2

Output: 3

Example 2:

Input: [1, 2, 3, 4, 5], 10

Output: "Error: Index out of bounds"

Use try-except block to handle IndexError.

def get_element(lst, index):
    try:
        return lst[index]
    except IndexError:
        return "Error: Index out of bounds"

print(get_element([1, 2, 3, 4, 5], 2))  # Output: 3
print(get_element([1, 2, 3, 4, 5], 10))  # Output: "Error: Index out of bounds"

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!