PYTHON
Implement a Fixed-Size History or Cache with collections.deque
Learn how to use Python's collections.deque to maintain a fixed-size history or cache, automatically dropping old items, ideal for recent activity logs or limited-size buffers.
from collections import deque
# Create a deque with a maximum size
MAX_HISTORY_SIZE = 5
history = deque(maxlen=MAX_HISTORY_SIZE)
# Add items to the history
history.append('user_login')
history.append('view_product_123')
history.append('add_to_cart_456')
print(f"Current history: {list(history)}")
history.append('checkout')
history.append('payment_successful')
print(f"History after 5 items: {list(history)}")
# Add another item; 'user_login' will be automatically dropped
history.append('view_order_details')
print(f"History after exceeding max size: {list(history)}")
# Example: Storing last N API calls or user actions
api_call_log = deque(maxlen=3)
api_call_log.append({'endpoint': '/users', 'status': 200})
api_call_log.append({'endpoint': '/products', 'status': 404})
api_call_log.append({'endpoint': '/orders', 'status': 201})
print(f"API Call Log: {list(api_call_log)}")
api_call_log.append({'endpoint': '/analytics', 'status': 500})
print(f"Updated API Call Log: {list(api_call_log)}")
How it works: The `collections.deque` (double-ended queue) is a versatile data structure, particularly useful when initialized with a `maxlen` parameter. This creates a fixed-size queue that automatically discards items from the opposite end (left, for `append`) once its maximum capacity is reached. This pattern is ideal for maintaining a history of recent actions, a limited cache, or logs where only the latest N entries are relevant, preventing unbounded memory growth in web applications.