PYTHON
Implement Efficient Queues and Fixed-Size History with `collections.deque`
Leverage Python's `collections.deque` for fast appends and pops from both ends, perfect for implementing queues, stacks, or managing a fixed-size history of recent items.
from collections import deque
# Basic deque (double-ended queue)
d = deque()
d.append('item1') # Add to the right
d.append('item2')
d.appendleft('item0') # Add to the left
print(f"Current deque: {list(d)}")
# Pop from both ends
popped_right = d.pop() # Remove from the right
popped_left = d.popleft() # Remove from the left
print(f"Popped right: {popped_right}, Popped left: {popped_left}")
print(f"Deque after pops: {list(d)}")
# Using deque as a fixed-size history buffer
history = deque(maxlen=3)
history.append('action1')
history.append('action2')
history.append('action3')
print(f"History (3 items): {list(history)}")
history.append('action4') # Oldest item ('action1') is automatically removed
print(f"History after action4: {list(history)}")
history.append('action5') # Oldest item ('action2') is automatically removed
print(f"History after action5: {list(history)}")
How it works: The `collections.deque` (double-ended queue) is a list-like container that allows for fast appends and pops from both ends of the sequence. Unlike regular lists, which are slow for inserts/deletes at the beginning, deques offer O(1) performance for these operations. This makes them perfect for implementing efficient queues (FIFO), stacks (LIFO), or fixed-size buffers like a history of recent actions, where old items are automatically discarded when the maximum length is reached.