PYTHON

Implement a Fixed-Size History or Log with collections.deque

Create a memory-efficient fixed-size buffer or log for recent items using Python's collections.deque, ideal for tracking last N actions or states in web applications with O(1) performance.

from collections import deque

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

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

# Add items to the history
history.append('action_1')
print(f"After action_1: {list(history)}")

history.append('action_2')
print(f"After action_2: {list(history)}")

history.append('action_3')
print(f"After action_3: {list(history)}")

# Adding a new item automatically removes the oldest one when maxlen is reached
history.append('action_4')
print(f"After action_4 (oldest removed): {list(history)}")

history.append('action_5')
print(f"After action_5 (oldest removed): {list(history)}")

# Accessing elements
print(f"Most recent action: {history[-1]}")
print(f"Oldest action in history: {history[0]}")
How it works: The `collections.deque` (double-ended queue) supports O(1) appends and pops from both ends. When initialized with a `maxlen` argument, it becomes a fixed-size queue. If a new item is added when the deque is full, the oldest item is automatically discarded, making it perfect for implementing a rotating log, recent activity history, or any scenario where you only care about the last N items.

Need help integrating this into your project?

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

Hire DigitalCodeLabs