PYTHON
Efficient Queue and Rotation with collections.deque
Learn to use Python's collections.deque for fast appends, pops, and rotations from both ends, perfect for implementing queues, command history, or fixed-size buffers in web services.
from collections import deque
# Creating a deque
d = deque(['apple', 'banana', 'cherry'])
print(f"Initial deque: {d}") # deque(['apple', 'banana', 'cherry'])
# Adding elements
d.append('date') # Add to the right
d.appendleft('fig') # Add to the left
print(f"After appends: {d}") # deque(['fig', 'apple', 'banana', 'cherry', 'date'])
# Removing elements
right_item = d.pop() # Remove from the right
left_item = d.popleft() # Remove from the left
print(f"Popped right: {right_item}, Popped left: {left_item}")
print(f"After pops: {d}") # deque(['apple', 'banana', 'cherry'])
# Limiting size (fixed-size buffer)
history = deque(maxlen=3)
history.append('command1')
history.append('command2')
history.append('command3')
print(f"History (full): {history}") # deque(['command1', 'command2', 'command3'], maxlen=3)
history.append('command4') # command1 is automatically evicted
print(f"History (newest): {history}") # deque(['command2', 'command3', 'command4'], maxlen=3)
# Rotating elements
d.rotate(1) # Rotate right by 1
print(f"Rotated right: {d}") # deque(['cherry', 'apple', 'banana'])
d.rotate(-2) # Rotate left by 2
print(f"Rotated left: {d}") # deque(['banana', 'cherry', 'apple'])
How it works: `collections.deque` (double-ended queue) is a list-like container optimized for fast appends and pops from both ends. Unlike lists, which are slow for inserts/deletes at the beginning, deques provide O(1) performance for these operations. It's ideal for implementing queues, stacks, or fixed-size history lists using the `maxlen` parameter, and also supports efficient rotation for cycling through items, useful in web services for managing tasks or recent activities.