PYTHON
Using collections.deque for Efficient Queues/Stacks
Explore collections.deque in Python for high-performance additions and removals from both ends, ideal for implementing queues, stacks, or history features in web apps.
from collections import deque
# Initialize a deque (double-ended queue)
task_queue = deque()
print(f"Initial queue: {list(task_queue)}")
# Add tasks to the right (end of the queue) - typical for queues
task_queue.append("Process User Registration")
task_queue.append("Send Welcome Email")
task_queue.append("Generate Report A")
print(f"After appending: {list(task_queue)}")
# Add high-priority task to the left (front of the queue)
task_queue.appendleft("Critical Security Alert")
print(f"After appendleft: {list(task_queue)}")
# Process tasks from the left (front of the queue) - FIFO for queues
print("
Processing tasks (FIFO):")
while task_queue:
task = task_queue.popleft()
print(f" - Completed: {task}")
print(f"Queue after processing: {list(task_queue)}")
# Using deque as a stack (LIFO)
# Add items to the right (top of the stack)
history_stack = deque()
history_stack.append("/dashboard")
history_stack.append("/settings")
history_stack.append("/profile/edit")
print(f"
History stack: {list(history_stack)}")
# Pop items from the right (top of the stack) - LIFO
print("Navigating back (LIFO):")
if history_stack:
current_page = history_stack.pop()
print(f" - Back from: {current_page}") # /profile/edit
if history_stack:
prev_page = history_stack.pop()
print(f" - Back from: {prev_page}") # /settings
print(f"History stack after popping: {list(history_stack)}")
How it works: This snippet demonstrates collections.deque (double-ended queue), a Python data structure optimized for fast appends and pops from both ends. Unlike lists, which are inefficient for pop(0) and insert(0, ...), deque operations like appendleft() and popleft() are O(1). This makes deque ideal for implementing efficient queues (FIFO) for background tasks, stacks (LIFO) for undo/redo features, or managing recent activity history in web applications.