PYTHON

Fixed-Size History/Log with collections.deque

Implement a fixed-size queue or log using Python's collections.deque for efficient appends and pops from both ends, ideal for managing recent items like user actions or limited caches.

from collections import deque

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

print(f"Initial deque: {list(recent_actions)}") # Output: Initial deque: []

recent_actions.append("User logged in")
recent_actions.append("Navigated to dashboard")
recent_actions.append("Viewed profile page")
print(f"After 3 appends: {list(recent_actions)}")
# Output: After 3 appends: ['User logged in', 'Navigated to dashboard', 'Viewed profile page']

recent_actions.append("Updated settings") # This will push out the oldest item
print(f"After 4th append: {list(recent_actions)}")
# Output: After 4th append: ['Navigated to dashboard', 'Viewed profile page', 'Updated settings']

# You can also append to the left
recent_actions.appendleft("System startup")
print(f"After appendleft: {list(recent_actions)}")
# Output: After appendleft: ['System startup', 'Navigated to dashboard', 'Viewed profile page']

# Pop elements
oldest_action = recent_actions.popleft()
print(f"Popped left: '{oldest_action}', Current: {list(recent_actions)}")
# Output: Popped left: 'System startup', Current: ['Navigated to dashboard', 'Viewed profile page']
How it works: `collections.deque` (double-ended queue) is a list-like container with fast appends and pops from either end. When a `maxlen` is specified, it acts as a fixed-size buffer, automatically discarding elements from the opposite end when its capacity is exceeded. This makes it perfect for maintaining a history of recent events, implementing a limited-size cache for recent user queries, or managing recent logs in a web application.

Need help integrating this into your project?

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

Hire DigitalCodeLabs