PYTHON
Manage Fixed-Length History/Log Buffer with collections.deque
Implement an efficient fixed-size circular buffer or history log using Python's collections.deque, perfect for storing recent events, user actions, or limited log entries in web applications.
from collections import deque
# Create a deque with a maximum length of 3
history_buffer = deque(maxlen=3)
print(f"Initial buffer: {list(history_buffer)}")
# Add items to the buffer
history_buffer.append("Event 1: User Login")
history_buffer.append("Event 2: Page View")
print(f"Buffer after two appends: {list(history_buffer)}")
history_buffer.append("Event 3: Item Added to Cart")
print(f"Buffer after third append: {list(history_buffer)}")
# When capacity is reached, adding a new item removes the oldest one
history_buffer.append("Event 4: Checkout Completed")
print(f"Buffer after fourth append (Event 1 removed): {list(history_buffer)}")
# Can also append/pop from left for other use cases
history_buffer.appendleft("Event 0: System Start")
print(f"Buffer after appendleft: {list(history_buffer)}") # Event 2 is removed
How it works: A `collections.deque` (double-ended queue) with a `maxlen` argument creates a fixed-size buffer. When new items are added via `append()` and the buffer is full, items are automatically removed from the opposite end (`popleft()`) to maintain the specified length. This makes `deque` exceptionally efficient for implementing fixed-length history logs, 'most recent' lists, or message queues, avoiding the overhead of list reallocations and shifts.