PYTHON

Implement an Efficient Fixed-Size History with Deque

Discover `collections.deque` for creating double-ended queues, perfect for maintaining fixed-size history logs or implementing efficient queues where elements are added and removed from both ends.

from collections import deque

# Example 1: Basic Deque operations
history = deque()
history.append("page1") # Add to the right
history.append("page2")
history.appendleft("page0") # Add to the left
print(f"Current history: {list(history)}") # Output: ['page0', 'page1', 'page2']

history.pop() # Remove from the right
print(f"After pop(): {list(history)}") # Output: ['page0', 'page1']

history.popleft() # Remove from the left
print(f"After popleft(): {list(history)}") # Output: ['page1']

# Example 2: Fixed-size history (e.g., last 3 visited pages)
recent_pages = deque(maxlen=3)
recent_pages.append("home")
recent_pages.append("products")
recent_pages.append("cart")
print(f"Recent pages (3 max): {list(recent_pages)}") # Output: ['home', 'products', 'cart']

recent_pages.append("checkout") # 'home' will be automatically removed
print(f"After 'checkout': {list(recent_pages)}") # Output: ['products', 'cart', 'checkout']

recent_pages.append("thank_you") # 'products' will be automatically removed
print(f"After 'thank_you': {list(recent_pages)}") # Output: ['cart', 'checkout', 'thank_you']

# Use case: Logging last N events
event_log = deque(maxlen=5)
for i in range(10):
    event_log.append(f"Event-{i+1}")
print(f"Last 5 events: {list(event_log)}")
How it works: `collections.deque` (double-ended queue) is a list-like container optimized for fast appends and pops from both ends. Unlike regular lists, `deque` offers O(1) performance for these operations. When initialized with a `maxlen` argument, it automatically discards elements from the opposite end when new items are added, making it perfect for maintaining fixed-size histories, caches, or event logs in web applications where efficiently tracking the most recent items is crucial.

Need help integrating this into your project?

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

Hire DigitalCodeLabs