List Index Validation

Write a Python function that takes a list and an index, and returns the element at that index. Raise an exception if the index is out of bounds.

Example 1:

Input: [1, 2, 3, 4, 5], 10 
Output: "Error: Index out of bounds."

Example 2:

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

Use the length of the list to validate the index.

def get_element(lst, idx):
    if idx >= len(lst) or idx < -len(lst):
        raise Exception("Error: Index out of bounds.")
    else:
        return lst[idx]

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

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!