TheAlgorithms/Python · error · IndexError

dequeue from empty queue

Error message

dequeue from empty queue

What it means

Raised by LinkedQueue.get() (data_structures/queues/linked_queue.py:131) when the singly-linked queue has no nodes. The class follows Python's queue conventions but signals underflow with a builtin IndexError instead of queue.Empty, matching doctest expectations. It is a normal control-flow guard, not a corruption bug.

Source

Thrown at data_structures/queues/linked_queue.py:131

            self.rear = node

    def get(self) -> Any:
        """
        >>> queue = LinkedQueue()
        >>> queue.get()
        Traceback (most recent call last):
            ...
        IndexError: dequeue from empty queue
        >>> queue = LinkedQueue()
        >>> for i in range(1, 6):
        ...     queue.put(i)
        >>> for i in range(1, 6):
        ...     assert queue.get() == i
        >>> len(queue)
        0
        """
        if self.is_empty():
            raise IndexError("dequeue from empty queue")
        assert isinstance(self.front, Node)
        node = self.front
        self.front = self.front.next
        if self.front is None:
            self.rear = None
        return node.data

    def clear(self) -> None:
        """
        >>> queue = LinkedQueue()
        >>> for i in range(1, 6):
        ...     queue.put(i)
        >>> queue.clear()
        >>> len(queue)
        0
        >>> str(queue)
        ''
        """

View on GitHub (pinned to f5988cc097)

Solutions

  1. Guard every get() with a len(queue) > 0 or not queue.is_empty() check
  2. If the doctests/scripts show the pattern, catch IndexError explicitly around get()
  3. Restructure the loop to consume exactly len(queue) items: while len(queue): item = queue.get()

Example fix

// before
while True:
    item = queue.get()  # IndexError on last iteration

# after
while len(queue):
    item = queue.get()
Defensive patterns

Strategy: validation

Validate before calling

if queue.is_empty():  # or: if not len(queue):
    raise LookupError('no items to dequeue')
item = queue.get()

Try / catch

try:
    item = queue.get()
except IndexError as e:
    if str(e) != 'dequeue from empty queue':
        raise
    item = None

Prevention

When it happens

Trigger: Calling get() more times than put() on a LinkedQueue: get() on a fresh queue, or draining 5 items after 5 put() calls and calling get() a 6th time (front and rear are both None).

Common situations: Consumer loops that dequeue until failure (while True: queue.get()), producer/consumer code where the consumer outruns the producer, and reusing a queue after clear().

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/e6172746c78a38b5. Report an issue: GitHub.