📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    Question

    A Python function get_element(arr, index) is supposed to

    return the element at a given index. def get_element(arr, index):     # Assume arr is a list of integers     if index >= 0 and index
    A Returns None; change index <= len(arr) to index < len(arr). Correct Answer Incorrect Answer
    B Returns None; change index <= len(arr) to index <= len(arr) - 1. Correct Answer Incorrect Answer
    C Raises IndexError; change index <= len(arr) to index < len(arr). Correct Answer Incorrect Answer
    D Raises IndexError; change index <= len(arr) to index <= len(arr) - 1. Correct Answer Incorrect Answer
    E Returns 30; no bug in the condition. Correct Answer Incorrect Answer

    Solution

    • Dry Run: o arr = [10, 20, 30] o len(arr) is 3. o Call get_element(arr, 3):  index is 3.  The if condition 3 >= 0 and 3 <= 3 evaluates to True.  The code then attempts to execute return arr[3].  Since arr has elements at indices 0, 1, and 2, attempting to access arr[3] (the 4th element) results in an IndexError. • Fix: To correctly check for valid indices, the upper bound should be strictly less than the length of the array. So, index < len(arr). • Why Correct Answer (C): Raises IndexError; change index <= len(arr) to index < len(arr). o The dry run confirms that an IndexError will be raised. o The suggested fix index < len(arr) correctly ensures that index is within the valid range 0 to len(arr) - 1.

    Practice Next
    ask-question