SaltyCrane Blog — Notes on JavaScript and web development

Python circular buffer

Here is a simple circular buffer, or ring buffer, implementation in Python. It is a first-in, first-out (FIFO) buffer with a fixed size.

class RingBuffer:
    def __init__(self, size):
        self.data = [None for i in xrange(size)]

    def append(self, x):
        self.data.pop(0)
        self.data.append(x)

    def get(self):
        return self.data
Here is an example where the buffer size is 4. Ten integers, 0-9, are inserted, one at a time, at the end of the buffer. Each iteration, the first element is removed from the front of the buffer.
buf = RingBuffer(4)
for i in xrange(10):
    buf.append(i)
    print buf.get()

Here are the results:
[None, None, None, 0]
[None, None, 0, 1]
[None, 0, 1, 2]
[0, 1, 2, 3]
[1, 2, 3, 4]
[2, 3, 4, 5]
[3, 4, 5, 6]
[4, 5, 6, 7]
[5, 6, 7, 8]
[6, 7, 8, 9]

References:

Comments


#1 stopgo commented on :

how do i print elements of buf.get?

I dont think Id be able to do

print buf.get[0] ?


#2 Jorge commented on :

As a note to those coming here for a circular queue/buffer, you should use collections.deque with the maxlen parameter set.

"Poping" the first element of a list is a slow operation (linear with the lenght of the list), so you should avoid it. For d(ouble)e(nded)ques, it's fast (constant time).