PYTHON

Implement a High-Performance Double-Ended Queue (Deque)

Learn how to use Python's `collections.deque` for efficient appends and pops from both ends, ideal for implementing queues, stacks, or recent item history in web applications.

from collections import deque

# As a queue (FIFO - First In, First Out)
my_queue = deque()
my_queue.append("task1")
my_queue.append("task2")
my_queue.append("task3")
print(f"Queue after appends: {my_queue}")
print(f"Processing: {my_queue.popleft()}") # Removes 'task1'
print(f"Processing: {my_queue.popleft()}") # Removes 'task2'
print(f"Queue after pops: {my_queue}")

# As a stack (LIFO - Last In, First Out)
my_stack = deque()
my_stack.append("itemA")
my_stack.append("itemB")
my_stack.append("itemC")
print(f"Stack after appends: {my_stack}")
print(f"Popping: {my_stack.pop()}") # Removes 'itemC'
print(f"Popping: {my_stack.pop()}") # Removes 'itemB'
print(f"Stack after pops: {my_stack}")

# Deque with a fixed maximum length (e.g., for recent history)
recent_searches = deque(maxlen=3)
recent_searches.append("python")
recent_searches.append("django")
recent_searches.append("flask")
print(f"Recent searches (3 items): {recent_searches}")
recent_searches.append("celery") # 'python' is automatically dropped
print(f"Recent searches after new item: {recent_searches}")
How it works: `collections.deque` (double-ended queue) provides a thread-safe, memory-efficient way to append and pop elements from both sides with O(1) performance. It's superior to Python's list for these operations, which incurs O(N) cost for `pop(0)` or `insert(0, item)`. It can be used as a simple queue (`append`, `popleft`), a stack (`append`, `pop`), or a fixed-size buffer using the `maxlen` parameter to automatically discard old items.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs