krahets/hello-algo · error · IndexError
佇列為空
Error message
佇列為空
What it means
Raised by the peek() method of a circular-array-based queue when _size equals 0. Since pop() delegates to peek() to read the front element before advancing _front, both operations fail on an empty queue. The _front pointer is meaningless when the queue is empty, so the guard prevents returning stale data.
Source
Thrown at zh-hant/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()
# 佇列首指標向後移動一位,若越過尾部,則返回到陣列頭部
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
- Check queue.is_empty() before calling peek() or pop()
- Use while not queue.is_empty() as the loop condition
- Wrap in try/except IndexError for defensive consumer code
Example fix
# before val = queue.peek() # after val = queue.peek() if not queue.is_empty() else None
Defensive patterns
Strategy: validation
Validate before calling
if not queue.is_empty():
val = queue.peek()
else:
val = None Try / catch
try:
val = queue.pop()
except IndexError:
val = None Prevention
- Check is_empty() before peek() or pop() in consumer code
- Use while not queue.is_empty() as the draining loop condition
- In producer-consumer setups, guard the consumer side with is_empty()
When it happens
Trigger: Calling peek() or pop() on a freshly constructed ArrayQueue with no push() calls; popping all elements and then calling pop() once more; a consumer reading faster than the producer enqueues.
Common situations: Producer-consumer pipelines where the queue is temporarily empty; BFS traversals that pop the last node and then call peek; testing with empty input sequences.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/b6b6e10b55763690.
Report an issue: GitHub.