Python LIFO implementation

May 27, 2008 – 2:13 am

I like this Python LIFO implementation:

class Lifo:
    """
    From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68436
    >>> lifo=Lifo()
    >>> lifo.append(1)
    >>> lifo.append(2)
    >>> print lifo.pop()
    2
    >>> print lifo.pop()
    1
    >>> print lifo.pop()
    Traceback (most recent call last):
        ...
    ValueError: need more than 0 values to unpack
    """
    def __init__(self):
        self.lifo = ()
    def append(self, data):
        self.lifo = (data, self.lifo)
    def pop(self):
        # Use tuple unpacking - popping an empty Lifo will
        # raise a ValueError, which is OK
        ret, self.lifo = self.lifo
        return ret

Post a Comment