python-3.xlifo

LIFO Queue that drops elements off the back end of it when length is exceeded?


I am not looking to preserve data. I am looking for a container that contains the last N items I stuffed in it, and allows items to fall off the back end of it and expire.

blocking_lifo = queue.LifoQueue(maxsize=2)
blocking_lifo.put("foo")
blocking_lifo.put("bar")
blocking_lifo.put("foo') # <-- fail

Not the behavior I am looking for. Instead, I'd like python to destroy what ever is in the back, and just store the two most recent things.

I also don't want to pop the head -- all I want is a LIFO vessel that has the latest element at position zero, and n elements (specified by me) that represent, exactly, the last n elements pushed in in a lifo order, with no steps or maintence by me to make the items that fall off the end of the queue fall off.

Is there a class for this kind of functionality in python3?


Solution

  • collections.deque with maxlen=2 does exactly what you want:

    >>> from collections import deque
    >>> l = deque(maxlen=2)
    >>> l.append("foo")
    >>> l.append("bar")
    >>> l.append("baz")
    >>> l
    deque(['bar', 'baz'], maxlen=2)