krahets/hello-algo · error · IndexError

Queue is empty

Error message

Queue is empty

What it means

LinkedListQueue.peek raises IndexError('Queue is empty') when _size is zero, blocking the self._front.val read on a None head. Because pop() calls peek() first, dequeueing from an empty queue surfaces the same exception. The guard encodes that front access requires a non-empty queue.

Source

Thrown at en/codes/python/chapter_stack_and_queue/linkedlist_queue.py:56

            self._rear = node
        # If the queue is not empty, add the node after the tail node
        else:
            self._rear.next = node
            self._rear = node
        self._size += 1

    def pop(self) -> int:
        """Dequeue"""
        num = self.peek()
        # Delete head node
        self._front = self._front.next
        self._size -= 1
        return num

    def peek(self) -> int:
        """Access front of the queue element"""
        if self.is_empty():
            raise IndexError("Queue is empty")
        return self._front.val

    def to_list(self) -> list[int]:
        """Convert to list for printing"""
        queue = []
        temp = self._front
        while temp:
            queue.append(temp.val)
            temp = temp.next
        return queue


"""Driver Code"""
if __name__ == "__main__":
    # Initialize queue
    queue = LinkedListQueue()

    # Elements enqueue

View on GitHub (pinned to 69932aed18)

Solutions

  1. Guard single access: `if not queue.is_empty(): head = queue.peek()`.
  2. Bound drains: `while not queue.is_empty(): x = queue.pop()`.
  3. Use queue.size() to control counted loops.
  4. Catch IndexError only for deliberate exception-based flow control.

Example fix

// before
head = queue.peek()  # raises if empty
// after
head = queue.peek() if not queue.is_empty() else None
Defensive patterns

Strategy: validation

Validate before calling

if not queue.is_empty():
    head = queue.peek()

Type guard

def queue_nonempty(q) -> bool:
    return not q.is_empty()

Try / catch

try:
    head = queue.peek()
except IndexError:
    head = None

Prevention

When it happens

Trigger: Calling peek() or pop() on a freshly constructed empty queue; calling after the last node was dequeued; unbounded drain loops; consumer running ahead of producer.

Common situations: BFS frontier dequeue; level-order traversal draining the queue; producer/consumer skew; test scaffolding popping more than pushed.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/34306589d6c29ac2. Report an issue: GitHub.