0

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?

erling
  • 411
  • 2
  • 5
  • 14
  • I realize now that if I define my deque to have a maxsize of 100 it will automatically call popleft() when I try to append more, seems as if this container fits me best! – erling Aug 14 '14 at 05:36
  • 1
    consider writing that as a self-answer with the reasons why deque is a better choice than another option (e.g. rolling your own or etc) – Adam Smith Aug 14 '14 at 05:37
  • For other ideas, google "circular buffer python". – NPE Aug 14 '14 at 05:43

1 Answers1

1

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.

Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284