PYTHON

Efficient Queues and Stacks with collections.deque

Master `collections.deque` in Python for high-performance additions and removals from both ends, ideal for implementing efficient queues and stacks in web applications.

from collections import deque

# Using deque as a Queue (FIFO - First In, First Out)
print("--- Queue (FIFO) Example ---")
request_queue = deque()
request_queue.append('User A Request') # Add to the right (end)
request_queue.append('User B Request')
request_queue.append('User C Request')
print(f"Queue after adding requests: {list(request_queue)}")

processed_request = request_queue.popleft() # Remove from the left (front)
print(f"Processed: '{processed_request}', Remaining queue: {list(request_queue)}")

processed_request = request_queue.popleft()
print(f"Processed: '{processed_request}', Remaining queue: {list(request_queue)}")

# Using deque as a Stack (LIFO - Last In, First Out)
print("
--- Stack (LIFO) Example ---")
history_stack = deque()
history_stack.append('Page 1') # Add to the right (top of stack)
history_stack.append('Page 2')
history_stack.append('Page 3')
print(f"Stack after adding pages: {list(history_stack)}")

current_page = history_stack.pop() # Remove from the right (top of stack)
print(f"Back from: '{current_page}', History stack: {list(history_stack)}")

current_page = history_stack.pop()
print(f"Back from: '{current_page}', History stack: {list(history_stack)}")

# Deque also supports extending from left
request_queue.extendleft(['Urgent Request']) 
print(f"Queue after extendleft: {list(request_queue)}")
How it works: `collections.deque` (double-ended queue) is a list-like container that supports O(1) time complexity for appending and popping elements from both ends. This makes it a highly efficient choice for implementing queues (First-In, First-Out) where elements are added at one end and removed from the other, and stacks (Last-In, First-Out) where elements are added and removed from the same end. Standard Python lists have O(n) complexity for `pop(0)` and `insert(0, ...)`, making `deque` preferable for these use cases.

Need help integrating this into your project?

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

Hire DigitalCodeLabs