We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

Simple Deque Class

November 29, 1997 | Fredrik Lundh

The Deque class (double-ended queue) is a variant of Stack that allows you to add and remove items at either end. It also provides a __getitem__ method that allows you to access any item in the list.

Note that this class uses a Python list as the underlying data structure, which means that operations at the “left end” of the queue isn’t quite as efficient as they could be, especially for larger queues.

Example: The Deque implementation (for Python 1.5.2 and later)
class Deque:

    def __init__(self):
        self.list = []

    def __len__(self):
        return len(self.list)

    def __getitem__(self, index):
        return self.list[index]

    def putfront(self, item):
        self.list.insert(0, item)

    def getfront(self):
        return self.list.pop(0)

    def putback(self, item):

    def getback(self):
        return self.list.pop() # default is last