krahets/hello-algo · error · IndexError

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

Error message

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

What it means

Raised by ArrayQueue.peek() in chapter_stack_and_queue/array_queue.py:51 — IndexError("очередь пуста" = "queue is empty"). peek returns self._nums[self._front]; on an empty queue _front is stale, so the guard is mandatory. pop() calls peek() first, so an empty pop surfaces as THIS error message, not a dedicated pop error.

Source

Thrown at ru/codes/python/chapter_stack_and_queue/array_queue.py:51

        # Вычислить указатель хвоста, указывающий на индекс хвоста + 1
        # С помощью операции взятия по модулю вернуть rear к началу после выхода за конец массива
        rear: int = (self._front + self._size) % self.capacity()
        # Добавить num в хвост очереди
        self._nums[rear] = num
        self._size += 1

    def pop(self) -> int:
        """Извлечь из очереди"""
        num: int = self.peek()
        # Указатель head сдвигается на одну позицию назад; если он выходит за конец, то возвращается в начало массива
        self._front = (self._front + 1) % self.capacity()
        self._size -= 1
        return num

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

    def to_list(self) -> list[int]:
        """Вернуть список для вывода"""
        res = [0] * self.size()
        j: int = self._front
        for i in range(self.size()):
            res[i] = self._nums[(j % self.capacity())]
            j += 1
        return res


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

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

View on GitHub (pinned to 69932aed18)

Solutions

  1. Guard: if not q.is_empty(): q.peek().
  2. Make is_empty() 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 were pushed. Reading the head before the first push.

Common situations: Consumer started before producer. Unbalanced push/pop. Draining loop without is_empty() guard.

Related errors


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