I completely agree with the idea of ββusing Python with a limited length deque , if it is available, and if not, then Michael Anderson's simple solution is quite adequate. (I saved both). But I just wanted to mention the third option of the ring buffer, which is often used for such tasks when low memory and high speed are important. (In other words, in situations where you probably aren't using Python: -p) For example, the Linux kernel uses this structure to store log messages generated during the boot process until the system logger starts.
A Python implementation might look like this:
class RingBuffer(object): def __init__(self, n): self._buf = [None] * n self._index = 0 self._valid = 0 def add(self, obj): n = len(self._buf) self._buf[self._index] = obj self._index += 1 if self._index == n self._index = 0 if self._valid < n: self._valid += 1 def __len__(self): return self._valid # could include other methods for accessing or modifying the contents
Basically, what he does is pre-allocate an array (in Python, a list) of the desired length and fill it with dummy values. The buffer also contains an βindexβ that indicates the next spot in the list to be filled with a value. Each time a value is added, it is stored in this place, and the index increases. When the index reaches the length of the array, it reset returns to zero. Here is an example (I use 0 instead of None for a dummy value just because it's faster to type):
[0,0,0,0,0] ^ # add 1 [1,0,0,0,0] ^ # add 2 [1,2,0,0,0] ^ # add 3 [1,2,3,0,0] ^ # add 4 [1,2,3,4,0] ^ # add 5 [1,2,3,4,5] ^ # add 6 [6,2,3,4,5] ^ # add 7 [6,7,3,4,5] ^
etc.