PYTHON
Manage Recent Items with collections.deque
Utilize Python's collections.deque (double-ended queue) for efficiently adding and removing items from both ends, perfect for managing history, logs, or limited-size caches.
from collections import deque
# Create a deque with a maximum length (e.g., last 5 visited pages)
history = deque(maxlen=5)
history.append('home_page')
history.append('products_page')
history.append('about_page')
print(f"Current history: {list(history)}")
history.append('contact_page')
history.append('privacy_page')
print(f"History after 5 items: {list(history)}")
# Adding a 6th item automatically removes the oldest one
history.append('terms_page')
print(f"History after 6 items (maxlen=5): {list(history)}")
# Deques also support appending/popping from the left (start)
history.appendleft('admin_dashboard')
print(f"History with item prepended: {list(history)}")
# Removing items
popped_right = history.pop()
popped_left = history.popleft()
print(f"Popped right: {popped_right}, Popped left: {popped_left}")
print(f"History after pops: {list(history)}")
How it works: A collections.deque (double-ended queue) allows for efficient appending and popping from both ends. When initialized with a maxlen, it acts as a fixed-size queue, automatically discarding the oldest item when a new one is added if the maximum length is exceeded. This makes it ideal for managing recent activity, log buffers, or 'last N items' features in web applications.