{"record":{"id":"df3b7cc7045f0601","repo":"TheAlgorithms/Python","slug":"queue-is-empty-df3b7c","errorCode":null,"errorMessage":"Queue is empty","messagePattern":"Queue is empty","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"data_structures/queues/queue_by_two_stacks.py","lineNumber":105,"sourceCode":"        1\n        >>> queue.get()\n        40\n        >>> queue.get()\n        Traceback (most recent call last):\n            ...\n        IndexError: Queue is empty\n        \"\"\"\n\n        # To reduce number of attribute look-ups in `while` loop.\n        stack1_pop = self._stack1.pop\n        stack2_append = self._stack2.append\n\n        if not self._stack2:\n            while self._stack1:\n                stack2_append(stack1_pop())\n\n        if not self._stack2:\n            raise IndexError(\"Queue is empty\")\n        return self._stack2.pop()\n\n\nif __name__ == \"__main__\":\n    from doctest import testmod\n\n    testmod()\n","sourceCodeStart":87,"sourceCodeEnd":113,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/data_structures/queues/queue_by_two_stacks.py#L87-L113","documentation":"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.","triggerScenarios":"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).","commonSituations":"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.","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"],"exampleFix":"// before\nwhile True:\n    process(queue.get())\n\n# after\nwhile queue:\n    process(queue.get())","handlingStrategy":"validation","validationCode":"if len(queue) == 0:  # counts both internal stacks\n    return None\nitem = queue.get()","typeGuard":null,"tryCatchPattern":"try:\n    item = queue.get()\nexcept IndexError as e:\n    if str(e) != 'Queue is empty':\n        raise\n    item = None","preventionTips":["This queue never blocks — do not port blocking queue.Queue.get() patterns to it","len(queue) correctly reports items split across _stack1 and _stack2"],"tags":["queue","two-stacks","index-error","python"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}