PYTHON

Managing Fixed-Size Queues with collections.deque

Utilize `collections.deque` with `maxlen` to create efficient fixed-size queues or circular buffers in Python, ideal for storing recent items, log entries, or implementing message caches.

from collections import deque

# Create a fixed-size queue (maxlen=3) to store recent user actions
recent_actions = deque(maxlen=3)

print("Initial deque:", list(recent_actions))

# Add actions
recent_actions.append("Login")
print("After 'Login':", list(recent_actions))

recent_actions.append("View Dashboard")
print("After 'View Dashboard':", list(recent_actions))

recent_actions.append("Edit Profile")
print("After 'Edit Profile':", list(recent_actions))

# When a new item is added, the oldest item is automatically removed
recent_actions.append("Logout")
print("After 'Logout' (Login should be gone):", list(recent_actions))

recent_actions.appendleft("Admin Override") # Add to the left (front)
print("After 'Admin Override' (View Dashboard should be gone):", list(recent_actions))

# Deques are efficient for adding/removing from both ends
print("
First action in queue (popleft):", recent_actions.popleft())
print("Deque after popleft:", list(recent_actions))

print("Last action in queue (pop):", recent_actions.pop())
print("Deque after pop:", list(recent_actions))
How it works: `collections.deque` (double-ended queue) is a list-like container optimized for fast appends and pops from both ends, offering O(1) performance compared to Python lists which can be O(N) for operations at the beginning. A key feature is its `maxlen` parameter, which creates a fixed-size queue or circular buffer. When new items are added to a full `deque`, the oldest items are automatically evicted, making it perfect for managing recent history (e.g., last 10 visited pages, recent API calls, message queues, log buffers) without manual trimming logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs