TheAlgorithms/Python · error · IndexError
Queue is empty
Error message
Queue is empty
What it means
Raised by QueueByTwoStacks.get() (data_structures/queues/queue_by_two_stacks.py:105). The queue amortizes movement: _stack1 receives put() items and is only flipped into _stack2 when _stack2 is empty. The error fires only when, after the flip attempt, both stacks are empty — i.e. the queue truly holds nothing.
Source
Thrown at data_structures/queues/queue_by_two_stacks.py:105
1
>>> queue.get()
40
>>> queue.get()
Traceback (most recent call last):
...
IndexError: Queue is empty
"""
# To reduce number of attribute look-ups in `while` loop.
stack1_pop = self._stack1.pop
stack2_append = self._stack2.append
if not self._stack2:
while self._stack1:
stack2_append(stack1_pop())
if not self._stack2:
raise IndexError("Queue is empty")
return self._stack2.pop()
if __name__ == "__main__":
from doctest import testmod
testmod()
View on GitHub (pinned to f5988cc097)
Solutions
- Check len(queue) == 0 before calling get() — it counts both internal stacks
- Use `while queue:` as the drain condition instead of exception-driven looping
- Catch IndexError if you deliberately detect end-of-data by exception
Example fix
// before
while True:
process(queue.get())
# after
while queue:
process(queue.get()) Defensive patterns
Strategy: validation
Validate before calling
if len(queue) == 0: # counts both internal stacks
return None
item = queue.get() Try / catch
try:
item = queue.get()
except IndexError as e:
if str(e) != 'Queue is empty':
raise
item = None Prevention
- This queue never blocks — do not port blocking queue.Queue.get() patterns to it
- len(queue) correctly reports items split across _stack1 and _stack2
When it happens
Trigger: get() on a freshly constructed QueueByTwoStacks(), or one get() beyond the number of put() calls (len(queue) reflects both stacks, so it drops to 0 first).
Common situations: Drain loops that call get() until failure, or producer/consumer code where get() races ahead of put() — note there is no blocking, unlike queue.Queue.get() which waits.
Related errors
- dequeue from empty queue
- Queue is empty
- Maximum queue size is 100
- Valid priorities are 0, 1, and 2
- All queues are empty
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/df3b7cc7045f0601.
Report an issue: GitHub.