PYTHON

Implement Bounded Queues and History with Python Deque

Learn to use Python's collections.deque for efficient appends and pops from both ends, ideal for implementing fixed-size history logs, queues, or rate limiters.

from collections import deque

def get_recent_activity(max_size=5):
    """
    Simulates a fixed-size log of recent user activities.
    """
    activity_log = deque(maxlen=max_size)
    return activity_log

# Example usage for a web application scenario
user_activities = get_recent_activity(3)
user_activities.append("User Alice logged in")
user_activities.append("User Alice viewed profile")
print("Current activity log:", list(user_activities))

user_activities.append("User Bob registered")
print("Current activity log (after Bob):", list(user_activities)) # Alice logged in should be removed

user_activities.append("User Alice updated settings")
print("Current activity log (after Alice update):", list(user_activities))

# Deque can also be used as a simple queue (FIFO)
task_queue = deque()
task_queue.append("Process payment A")
task_queue.append("Send notification B")
print("Next task to process:", task_queue.popleft())
print("Remaining tasks:", list(task_queue))
How it works: `collections.deque` (double-ended queue) provides a list-like container with fast appends and pops from both ends. When initialized with `maxlen`, it automatically discards elements from the opposite end when its size exceeds the maximum, making it perfect for managing fixed-size histories, recent items, or implementing basic queues/stacks in web applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs