PYTHON
Manage Recent Activities with `collections.deque`
Discover how `collections.deque` provides an efficient double-ended queue for managing limited-size histories, logs, or "most recent" data in web applications.
from collections import deque
# Create a deque with a maximum length (e.g., last 5 visited pages)
history = deque(maxlen=5)
print(f"Initial history: {list(history)}")
history.append("homepage")
history.append("products")
history.append("about_us")
print(f"After 3 appends: {list(history)}")
history.append("contact")
history.append("blog")
print(f"After 5 appends: {list(history)}")
# When maxlen is reached, old items are automatically discarded
history.append("privacy_policy")
print(f"After 6th append (oldest removed): {list(history)}")
# Can also append to the left or pop from either side
history.appendleft("admin_dashboard")
print(f"After appendleft: {list(history)}")
last_visited = history.pop()
print(f"Popped last item: {last_visited}, History: {list(history)}")
first_visited = history.popleft()
print(f"Popped first item: {first_visited}, History: {list(history)}")
How it works: `collections.deque` (double-ended queue) is a list-like container that supports fast appends and pops from both ends. When initialized with a `maxlen`, it automatically discards the oldest items upon new additions, making it perfect for implementing fixed-size caches, activity logs, or history features where you only care about the most recent N items in web applications.