PYTHON

Implement a Fixed-Size History or Buffer

Use `collections.deque` to create a fixed-size queue or history buffer that automatically discards older items when new ones are added, perfect for logs or recent actions.

from collections import deque

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

recent_actions.append("User logged in")
recent_actions.append("Navigated to dashboard")
recent_actions.append("Clicked on profile")
print(list(recent_actions))
# Output: ['User logged in', 'Navigated to dashboard', 'Clicked on profile']

recent_actions.append("Updated profile picture") # Oldest item "User logged in" is automatically removed
print(list(recent_actions))
# Output: ['Navigated to dashboard', 'Clicked on profile', 'Updated profile picture']

recent_actions.appendleft("System event occurred") # Add to the beginning, pushes items out from right
print(list(recent_actions))
# Output: ['System event occurred', 'Navigated to dashboard', 'Clicked on profile']
How it works: `collections.deque` (double-ended queue) is a list-like container that supports fast appends and pops from both ends. By specifying a `maxlen` during initialization, the deque becomes a fixed-size circular buffer. This means that when new items are added beyond the maximum length, elements are automatically removed from the opposite end, making it ideal for managing recent history, log buffers, or streaming data with limited memory.

Need help integrating this into your project?

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

Hire DigitalCodeLabs