PYTHON

Implementing a Fixed-Size Rotating Buffer with `collections.deque`

Build an efficient fixed-size rotating buffer using Python's `collections.deque`. Ideal for managing recent activity logs or processing data streams with automatic old-item eviction.

from collections import deque

# Create a fixed-size deque (maxlength) for a rotating buffer
# When new items are added, old items are automatically evicted if buffer is full
recent_logs = deque(maxlen=3)

print(f"Initial buffer: {list(recent_logs)}")

recent_logs.append("Log entry 1")
print(f"Buffer after 'Log entry 1': {list(recent_logs)}")

recent_logs.append("Log entry 2")
print(f"Buffer after 'Log entry 2': {list(recent_logs)}")

recent_logs.append("Log entry 3")
print(f"Buffer after 'Log entry 3': {list(recent_logs)}")

# Adding a new item will evict the oldest ('Log entry 1')
recent_logs.append("Log entry 4")
print(f"Buffer after 'Log entry 4': {list(recent_logs)}")

recent_logs.append("Log entry 5")
print(f"Buffer after 'Log entry 5': {list(recent_logs)}")

# Deques also support efficient appends/pops from both ends
print(f"Current buffer: {list(recent_logs)}")
recent_logs.appendleft("Log entry 0") # Adds to the left, evicts from right if full
print(f"Buffer after 'Log entry 0' (appendleft): {list(recent_logs)}")

# You can iterate over it like a list
print("Iterating through recent logs:")
for log in recent_logs:
    print(f"- {log}")
How it works: The `collections.deque` (double-ended queue) is a list-like container with fast appends and pops from either end. Crucially, when initialized with the `maxlen` argument, it acts as a fixed-size rotating buffer. As new items are added to a full deque, items from the opposite end are automatically discarded, maintaining the specified maximum length. This makes it perfect for scenarios requiring a history of recent items, such as transaction logs, cache implementations, or sliding window algorithms, without manual eviction logic.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs