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


    Question

    A Python Queue class uses a list. Its is_empty method is

    implemented incorrectly. class Queue:     def __init__(self):         self._items = []     def enqueue(self, item):         self._items.append(item)     def dequeue(self):         if not self.is_empty():             return self._items.pop(0)         else:             raise IndexError("Queue is empty")     def is_empty(self):         return self._items is None # Potential bug here If q = Queue() is created, and then q.dequeue() is called without any prior enqueue operations, what will happen?
    A It will correctly raise an IndexError("Queue is empty"). Correct Answer Incorrect Answer
    B It will return None. Correct Answer Incorrect Answer
    C It will raise an AttributeError. Correct Answer Incorrect Answer
    D It will raise a TypeError. Correct Answer Incorrect Answer
    E It will raise an IndexError because _items is an empty list, not None. Correct Answer Incorrect Answer

    Solution

    • Dry Run: o q = Queue(): q._items is initialized as an empty list []. o q.dequeue() is called:  It first checks if not self.is_empty():.  self.is_empty() evaluates self._items is None.  Since self._items is [] (an empty list) and not None, the expression [] is None is False.  Therefore, self.is_empty() returns False.  The if condition becomes if not False:, which is if True:.  The code inside the if block executes: return self._items.pop(0).  self._items is []. Calling pop(0) on an empty list raises an IndexError. • Why Correct Answer (E): It will raise an IndexError because _items is an empty list, not None. o This accurately describes the flow of execution and the resulting error. The is_empty method incorrectly returns False for an empty queue, leading to an attempt to pop from an empty list.

    Practice Next
    ask-question