krahets/hello-algo · error · IndexError
キューが空です
Error message
キューが空です
What it means
This IndexError (Japanese: 'キューが空です' = 'queue is empty') is raised by ArrayQueue.peek() (array_queue.py:51) when _size == 0. peek() returns _nums[_front]; pop() calls peek() first, so the same exception propagates through pop() on an empty queue. The circular-array layout means _front alone does not indicate a valid element — only _size > 0 does.
Source
Thrown at ja/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()
# 先頭ポインタを1つ後ろへ進め、末尾を越えたら配列先頭に戻す
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
- Guard with `if not queue.is_empty(): queue.peek()`.
- Drain with `while not queue.is_empty(): queue.pop()`.
- Base pop-count on queue.size(), not capacity or a stale length.
- In producer/consumer code, check is_empty() before attempting to consume.
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() first — guard pop the same way Type guard
def queue_has_front(q: ArrayQueue) -> bool:
return not q.is_empty() Try / catch
try:
val = queue.pop()
except IndexError:
val = None Prevention
- Check is_empty() before peek() or pop() (pop delegates to peek).
- Base consume counts on queue.size(), not capacity.
- Drain with `while not queue.is_empty():`.
- In producer/consumer flows, gate consumption on is_empty().
When it happens
Trigger: Calling peek() or pop() on a freshly constructed ArrayQueue. Calling pop() more times than push(). The constructor sets _size = 0 and _front = 0, so any immediate peek/pop raises.
Common situations: Consuming faster than producing. Looping a fixed number of pops based on capacity rather than size(). Forgetting that pop() delegates to peek() and will raise the same IndexError.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/ac57dd02488fb09c.
Report an issue: GitHub.