TheAlgorithms/Python · error · IndexError

Queue is empty

Error message

Queue is empty

What it means

Raised by QueueByList.get() (data_structures/queues/queue_by_list.py:95) when self.entries is empty. The underlying store is a plain list and get() returns self.entries.pop(0), so the guard prevents popping from an empty list and substitutes a clear IndexError message. Length is available via len(queue) and the repr is Queue((...)).

Source

Thrown at data_structures/queues/queue_by_list.py:95

        >>> queue.get()
        10
        >>> queue.put(40)
        >>> queue.get()
        20
        >>> queue.get()
        30
        >>> len(queue)
        1
        >>> queue.get()
        40
        >>> queue.get()
        Traceback (most recent call last):
            ...
        IndexError: Queue is empty
        """

        if not self.entries:
            raise IndexError("Queue is empty")
        return self.entries.pop(0)

    def rotate(self, rotation: int) -> None:
        """Rotate the items of the Queue `rotation` times

        >>> queue = QueueByList([10, 20, 30, 40])
        >>> queue
        Queue((10, 20, 30, 40))
        >>> queue.rotate(1)
        >>> queue
        Queue((20, 30, 40, 10))
        >>> queue.rotate(2)
        >>> queue
        Queue((40, 10, 20, 30))
        """

        put = self.entries.append
        get = self.entries.pop

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pre-check with `if queue:` or len(queue) before get()
  2. Wrap drain loops in `while len(queue): queue.get()`
  3. Catch IndexError if you intentionally run-until-empty

Example fix

// before
item = queue.get()

# after
item = queue.get() if len(queue) else None
Defensive patterns

Strategy: validation

Validate before calling

if not queue.entries:  # or: if not len(queue)
    return None
item = queue.get()

Try / catch

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

Prevention

When it happens

Trigger: Calling get() on QueueByList() with no constructor argument, or calling get() more times than entries exist (the doctest shows get() after draining 10,20,30,40).

Common situations: Reusing a queue across iterations without re-filling, consumer loops that assume the producer already ran, and off-by-one counts after rotate() (rotate does not consume items, so mismatches usually come from elsewhere).

Related errors


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