I fully agree with the idea of using Python's limited-length deque if it's available, and if not, Michael Anderson's simple solution is quite adequate. (I upvoted both) But I just wanted to mention the third option of a ring buffer, which is often used for this kind of task when low memory footprint and high execution speed are important. (In other words, in situations when you probably wouldn't be using Python :-p) For example, the Linux kernel uses this structure to store log messages generated during the boot process, before the system logger starts.
A Python implementation could 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 it does is preallocate an array (in Python, a list) of the desired length and fill it with dummy values. The buffer also contains an "index" which points to the next spot in the list that should be filled with a value. Each time a value is added, it's stored in that spot and the index is incremented. When the index reaches the length of the array, it's reset back to zero. Here's an example (I'm using 0 instead of None for the dummy value just because it's quicker 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]
^
and so on.