PYTHON
Manage Fixed-Size Collections with Python's `collections.deque`
Utilize Python's `collections.deque` (double-ended queue) to efficiently manage fixed-size lists, perfect for maintaining history, log buffers, or recent activity feeds.
from collections import deque
# Create a deque with a maximum size of 3
recent_activities = deque(maxlen=3)
print(f"Initial deque: {list(recent_activities)}")
recent_activities.append("User A logged in")
print(f"After 1st append: {list(recent_activities)}")
recent_activities.append("User B viewed profile")
print(f"After 2nd append: {list(recent_activities)}")
recent_activities.append("User C updated settings")
print(f"After 3rd append: {list(recent_activities)}")
# When a new item is added and maxlen is reached, the oldest item is automatically removed
recent_activities.append("User A posted comment")
print(f"After 4th append (oldest removed): {list(recent_activities)}")
# You can also append to the left or pop from either end
recent_activities.appendleft("System alert")
print(f"After appendleft: {list(recent_activities)}")
popped_right = recent_activities.pop()
print(f"Popped from right: {popped_right}, Deque: {list(recent_activities)}")
popped_left = recent_activities.popleft()
print(f"Popped from left: {popped_left}, Deque: {list(recent_activities)}")
How it works: The `collections.deque` (double-ended queue) is a list-like container optimized for fast appends and pops from both ends. When initialized with a `maxlen` argument, it becomes a fixed-size queue, automatically discarding the oldest item when a new item is added and the maximum length is reached. This makes it ideal for managing recent activity logs, keeping track of a fixed number of visited pages, or implementing simple caching mechanisms where older items are naturally evicted.