← Back to all snippets
PYTHON

Implement Efficient Queues and Stacks with `collections.deque`

Utilize Python's `collections.deque` (double-ended queue) for fast appends and pops from both ends, making it ideal for implementing efficient queues, stacks, or sliding window algorithms.

from collections import deque

# As a Queue (FIFO - First-In, First-Out)
my_queue = deque()
my_queue.append("task1") # Enqueue
my_queue.append("task2")
print(f"Queue after appends: {my_queue}")
print(f"Dequeuing: {my_queue.popleft()}") # Dequeue
print(f"Queue after popleft: {my_queue}")

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

# Limiting size (sliding window)
window = deque(maxlen=3)
for i in range(10):
    window.append(i)
    print(f"Window: {list(window)}") # Convert to list for clear printing
How it works: `collections.deque` provides a thread-safe, memory-efficient double-ended queue. It allows O(1) time complexity for appending and popping elements from both ends, unlike standard Python lists which can be O(N) for `pop(0)` or `insert(0, ...)`. This makes `deque` excellent for implementing queues (FIFO), stacks (LIFO), or fixed-size sliding window patterns where older elements are automatically discarded, common in message processing or real-time analytics.

Need help integrating this into your project?

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

Hire DigitalCodeLabs