PYTHON

Fixed-Size History Buffer with collections.deque

Maintain a rotating, fixed-size history or log of recent events or commands using Python's `collections.deque` with `maxlen` for efficient appends and removals.

from collections import deque

# Create a deque with a maximum length of 3
history = deque(maxlen=3)

print(f"Initial history: {list(history)}")

history.append("User logged in")
print(f"After 1st append: {list(history)}")

history.append("Viewed dashboard")
print(f"After 2nd append: {list(history)}")

history.append("Edited profile")
print(f"After 3rd append: {list(history)}")

history.append("Updated settings") # This will automatically remove the oldest item
print(f"After 4th append (oldest removed): {list(history)}")

history.appendleft("Initial page load") # Add to the beginning
print(f"After appendleft (oldest removed): {list(history)}")

# Accessing elements
print(f"Most recent event: {history[-1]}")
print(f"Oldest event: {history[0]}")

# Expected output:
# Initial history: []
# After 1st append: ['User logged in']
# After 2nd append: ['User logged in', 'Viewed dashboard']
# After 3rd append: ['User logged in', 'Viewed dashboard', 'Edited profile']
# After 4th append (oldest removed): ['Viewed dashboard', 'Edited profile', 'Updated settings']
# After appendleft (oldest removed): ['Initial page load', 'Viewed dashboard', 'Edited profile']
# Most recent event: Edited profile
# Oldest event: Initial page load
How it works: `collections.deque` (double-ended queue) is ideal for implementing fixed-size history buffers or logs. By setting the `maxlen` parameter during initialization, the deque automatically discards elements from the opposite end when it reaches its capacity and new elements are added. This provides efficient `O(1)` time complexity for appending and popping from both ends, making it perfect for managing a rolling window of data, such as recent user actions or system events.

Need help integrating this into your project?

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

Hire DigitalCodeLabs