krahets/hello-algo · error · IndexError

очередь пуста

Error message

очередь пуста

What it means

Raised by LinkedListQueue.peek() in chapter_stack_and_queue/linkedlist_queue.py:56 — IndexError("очередь пуста" = "queue is empty"). peek returns self._front.val; on an empty queue self._front is None, so the guard prevents an AttributeError. pop() calls peek() first, so an empty pop surfaces as THIS message rather than a dedicated pop error.

Source

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

            self._rear = node
        # Если очередь не пуста, добавить этот узел после хвостового узла
        else:
            self._rear.next = node
            self._rear = node
        self._size += 1

    def pop(self) -> int:
        """Извлечь из очереди"""
        num = self.peek()
        # Удалить головной узел
        self._front = self._front.next
        self._size -= 1
        return num

    def peek(self) -> int:
        """Доступ к элементу в начале очереди"""
        if self.is_empty():
            raise IndexError("очередь пуста")
        return self._front.val

    def to_list(self) -> list[int]:
        """Преобразовать в список для вывода"""
        queue = []
        temp = self._front
        while temp:
            queue.append(temp.val)
            temp = temp.next
        return queue


"""Driver Code"""
if __name__ == "__main__":
    # Инициализация очереди
    queue = LinkedListQueue()

    # Добавление элемента в очередь

View on GitHub (pinned to 69932aed18)

Solutions

  1. Guard: if not q.is_empty(): q.peek().
  2. Use is_empty() as the loop condition for consumption.
  3. Wrap pop in try/except IndexError since pop delegates to peek.
  4. Seed the queue before starting consumers.

Example fix

// before
x = q.pop()
// after
x = q.pop() if not q.is_empty() else None
Defensive patterns

Strategy: validation

Validate before calling

def safe_peek(q):
    return q.peek() if not q.is_empty() else None

Type guard

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

Try / catch

try:
    x = q.pop()  # pop delegates to peek
except IndexError:
    x = None

Prevention

When it happens

Trigger: Calling peek() or pop() on an empty queue. Consuming more items than pushed. Reading the front before the first enqueue.

Common situations: Consumer started before producer. Draining loop without is_empty() guard. Reusing the queue across batches without resetting checks.

Related errors


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