krahets/hello-algo · error · IndexError

キューが空です

Error message

キューが空です

What it means

This IndexError (Japanese: 'キューが空です' = 'queue is empty') is raised by LinkedListQueue.peek() (linkedlist_queue.py:56) when _size == 0. peek() returns _front.val; the guard avoids dereferencing _front (None). pop() calls peek() first, so the same exception propagates through pop() on an empty queue. The linked-list queue is unbounded, so 'empty' is the only failure mode.

Source

Thrown at ja/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 with `if not queue.is_empty(): queue.peek()`.
  2. Drain with `while not queue.is_empty(): queue.pop()`.
  3. Base consume counts on queue.size().
  4. In producer/consumer flows, check is_empty() before consuming.

Example fix

// before
val = queue.pop()  # IndexError on empty

// after
val = queue.pop() if not queue.is_empty() else None
Defensive patterns

Strategy: validation

Validate before calling

if not queue.is_empty():
    val = queue.peek()
# pop() calls peek() — guard pop() the same way

Type guard

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

Try / catch

try:
    val = queue.pop()
except IndexError:
    val = None

Prevention

When it happens

Trigger: Calling peek() or pop() on a freshly constructed LinkedListQueue (size 0). Calling pop() more times than push(). _front is None until the first push sets both _front and _rear.

Common situations: Consumer outrunning producer in a queue-based pipeline. Looping pops by a fixed count rather than by size(). Forgetting pop() delegates to peek() and raises identically.

Related errors


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