Sub topic 7
Implementing push and pop
This chapter assumes you know zero-based array indexing, the FIFO queue idea (enqueue and dequeue), and the modulo operator. It also assumes you have read the earlier chapters on head and tail indices and on telling full from empty. Here you turn that model into working code.
The state you need
A ring buffer with a count field needs three pieces of state besides the array:
_buf: a fixed-size list that never grows or shrinks._head: the index of the oldest item, which is the next onepopreturns._count: the number of stored items.
The tail is not stored. It is computed as (head + count) % capacity. Because count is stored, a full buffer (count == capacity) can never be confused with an empty one (count == 0).
The implementation
class RingBuffer:
def __init__(self, capacity):
if capacity <= 0:
raise ValueError("capacity must be positive")
self._buf = [None] * capacity
self._head = 0 # index of the oldest item
self._count = 0 # number of stored items
def __len__(self):
return self._count
def push(self, item):
if self._count == len(self._buf):
raise OverflowError("buffer full")
tail = (self._head + self._count) % len(self._buf)
self._buf[tail] = item
self._count += 1
def pop(self):
if self._count == 0:
raise IndexError("buffer empty")
item = self._buf[self._head]
self._buf[self._head] = None
self._head = (self._head + 1) % len(self._buf)
self._count -= 1
return item
rb = RingBuffer(3)
rb.push(1)
rb.push(2)
rb.push(3)
print(rb.pop()) # 1
rb.push(4) # reuses the freed slot at index 0
print([rb.pop(), rb.pop(), rb.pop()]) # [2, 3, 4]Following the wrap
After the first three pushes, the slots hold [1, 2, 3] and head is 0. The first pop returns 1 and moves head to 1, leaving count at 2. The next push(4) computes tail = (1 + 2) % 3 = 0. The modulo sends the write back to index 0, the slot that pop just freed. Nothing was shifted or reallocated.
Complexity
Both operations do a fixed number of steps: one comparison, one index calculation, one array access, and one or two integer updates. Each is O(1) regardless of how many items are stored. The memory is O(capacity) and fixed at construction. A queue built on a plain list with list.pop(0) shifts every remaining element on each dequeue, which costs O(n).
Common errors
- Checking the wrong condition.
pushmust test for full andpopmust test for empty. Swapping them letspopreturn stale data. - Skipping the modulo on
head. Without% len(self._buf),headruns past the end of the array and raisesIndexError. - Writing before checking. If
pushwrites first and then notices the buffer is full, it has already destroyed the oldest item. - Leaving old references in place.
popsets the slot toNoneso the buffer does not keep dead objects alive. In C this step is usually unnecessary.
Exercise
A RingBuffer has capacity 5. After pushing 5 items and popping 2, head is 2 and count is 3. At which array index does the next push write?
Show answer
Index 0. The tail is (2 + 3) % 5 = 0, so the write wraps around to the start of the array. After that push, count is 4.