PYTHON
Implement Queues and Stacks with `collections.deque`
Efficiently manage data with a double-ended queue (`deque`) in Python, ideal for implementing FIFO queues or LIFO stacks in web application task processing.
from collections import deque
# Implementing a Queue (FIFO - First-In, First-Out)
print("--- Queue Example ---")
task_queue = deque()
task_queue.append("Task A")
task_queue.append("Task B")
task_queue.append("Task C")
print(f"Queue after appends: {list(task_queue)}")
print(f"Processing: {task_queue.popleft()}") # Removes 'Task A'
print(f"Processing: {task_queue.popleft()}") # Removes 'Task B'
print(f"Queue remaining: {list(task_queue)}")
# Implementing a Stack (LIFO - Last-In, First-Out)
print("
--- Stack Example ---")
history_stack = deque()
history_stack.append("Page 1")
history_stack.append("Page 2")
history_stack.append("Page 3")
print(f"Stack after appends: {list(history_stack)}")
print(f"Going back: {history_stack.pop()}") # Removes 'Page 3'
print(f"Going back: {history_stack.pop()}") # Removes 'Page 2'
print(f"Stack remaining: {list(history_stack)}")
# Adding to the left (e.g., for priority tasks or reversing order)
task_queue.appendleft("Urgent Task")
print(f"Queue with urgent task: {list(task_queue)}")
How it works: `collections.deque` (double-ended queue) is a list-like container with fast appends and pops from both ends. This makes it an excellent choice for implementing both FIFO (First-In, First-Out) queues, commonly used for task processing or message handling, and LIFO (Last-In, First-Out) stacks, often used for history tracking or undo functionalities. Unlike standard lists, `deque` offers O(1) time complexity for appending and popping elements from either end, making it more efficient for these operations.