Search code examples
pythonperformancecontainers

Python what container with constant size and constantly changing elements


Say I want a container to store some value returned from a sensor at 50Hz. I want store the present value, and also the last 100 so that I can say something about how the value is changing. What kind of container am I looking for? I was thinking maybe deque, and something like this:

def updateValue(data):
    self._value.append(data)
    self._value.popleft()

So every 20ms updateValue is called and appends an element on the end, and removes one from the start. Is there a more efficient way to do this?


Solution

  • deque is the correct container type.

    I would pass in the optional maxlen argument so that the queue length is bound to 100:

    If maxlen is not specified or is None, deques may grow to an arbitrary length. Otherwise, the deque is bounded to the specified maximum length. Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end. Bounded length deques provide functionality similar to the tail filter in Unix. They are also useful for tracking transactions and other pools of data where only the most recent activity is of interest.