queue implementation using two stacks from collections abc import iterable from typing import generic typevar t typevart class queuebytwostacksgenerict def initself iterable iterablet none none none self stack1 listt listiterable or self stack2 listt def lenself int return lenself stack1 lenself stack2 def reprself str return fqueuetupleself stack2 1 self stack1 def putself item t none self stack1 appenditem def getself t to reduce number of attribute lookups in while loop stack1pop self stack1 pop stack2append self stack2 append if not self stack2 while self stack1 stack2appendstack1pop if not self stack2 raise indexerrorqueue is empty return self stack2 pop if name main from doctest import testmod testmod queuebytwostacks queue queuebytwostacks 10 20 30 queue 10 20 30 queuebytwostacks i 2 for i in range 1 4 queue 1 4 9 len queuebytwostacks 0 from string import ascii_lowercase len queuebytwostacks ascii_lowercase 26 queue queuebytwostacks for i in range 1 11 queue put i len queue 10 for i in range 2 queue get 1 2 len queue 8 queue queuebytwostacks queue queue str queue queue queue put 10 queue queue 10 queue put 20 queue put 30 queue queue 10 20 30 put item into the queue queue queuebytwostacks queue put 10 queue put 20 len queue 2 queue queue 10 20 get item from the queue queue queuebytwostacks 10 20 30 queue get 10 queue put 40 queue get 20 queue get 30 len queue 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
from collections.abc import Iterable
from typing import Generic, TypeVar

_T = TypeVar("_T")


class QueueByTwoStacks(Generic[_T]):
    def __init__(self, iterable: Iterable[_T] | None = None) -> None:
        
        self._stack1: list[_T] = list(iterable or [])
        self._stack2: list[_T] = []

    def __len__(self) -> int:
        

        return len(self._stack1) + len(self._stack2)

    def __repr__(self) -> str:
        
        return f"Queue({tuple(self._stack2[::-1] + self._stack1)})"

    def put(self, item: _T) -> None:
        

        self._stack1.append(item)

    def get(self) -> _T:
        

        
        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()