PYTHON
Implement Efficient Queues and Deques with `collections.deque`
Discover `collections.deque` in Python for fast appends and pops from both ends, ideal for managing queues, history lists, or implementing a circular buffer.
from collections import deque
# Create a deque with an initial list
history = deque(['page1', 'page2', 'page3'])
print(f"Initial history: {history}")
# Append to the right (default behavior of a list)
history.append('page4')
print(f"After append: {history}")
# Append to the left (efficient operation)
history.appendleft('page0')
print(f"After appendleft: {history}")
# Pop from the right (efficient operation)
last_page = history.pop()
print(f"Popped last page: {last_page}, Current history: {history}")
# Pop from the left (efficient operation)
first_page = history.popleft()
print(f"Popped first page: {first_page}, Current history: {history}")
# Limit the size of the deque (circular buffer)
recent_searches = deque(maxlen=3)
recent_searches.append('python')
recent_searches.append('flask')
recent_searches.append('django')
print(f"Recent searches (full): {recent_searches}")
recent_searches.append('api') # 'python' will be automatically removed
print(f"Recent searches (after new append): {recent_searches}")
How it works: `collections.deque` (double-ended queue) is a list-like container that supports fast appends and pops from both its left and right ends (O(1) complexity). Unlike standard Python lists, which have O(N) complexity for `insert(0, item)` or `pop(0)`, `deque` operations are always efficient. This makes it perfect for implementing queues, managing a fixed-size history or log buffer, or any scenario requiring efficient additions and removals from either end of a sequence. The `maxlen` parameter allows for automatic trimming, making it a natural choice for circular buffers.