PYTHON
Implementing Queues and Stacks with `collections.deque`
Efficiently manage ordered collections like queues (FIFO) and stacks (LIFO) using Python's `collections.deque` for fast appends and pops from both ends.
from collections import deque
# --- Using deque as a Queue (FIFO: First-In, First-Out) ---
print("--- Queue Example ---")
request_queue = deque()
# Add items to the end of the queue
request_queue.append("Request 1: Process User Data")
request_queue.append("Request 2: Generate Report")
request_queue.append("Request 3: Send Email Notification")
print(f"Current queue: {list(request_queue)}")
# Process items from the front of the queue
if request_queue:
next_request = request_queue.popleft()
print(f"Processing: {next_request}")
print(f"Queue after popleft: {list(request_queue)}")
if request_queue:
next_request = request_queue.popleft()
print(f"Processing: {next_request}")
print(f"Queue after second popleft: {list(request_queue)}")
# --- Using deque as a Stack (LIFO: Last-In, First-Out) ---
print("
--- Stack Example ---")
call_stack = deque()
# Push items onto the stack (append to the right)
call_stack.append("Function A: authenticate_user()")
call_stack.append("Function B: load_profile()")
call_stack.append("Function C: render_page()")
print(f"Current stack: {list(call_stack)}")
# Pop items from the top of the stack (pop from the right)
if call_stack:
last_call = call_stack.pop()
print(f"Exiting: {last_call}")
print(f"Stack after pop: {list(call_stack)}")
if call_stack:
last_call = call_stack.pop()
print(f"Exiting: {last_call}")
print(f"Stack after second pop: {list(call_stack)}")
How it works: `collections.deque` (double-ended queue) is a versatile data structure offering O(1) time complexity for appending and popping elements from both ends. This makes it ideal for implementing queues (First-In, First-Out) using `append()` and `popleft()`, and stacks (Last-In, First-Out) using `append()` and `pop()`. It's significantly more efficient than standard Python lists for these operations, especially with large collections, making it suitable for managing tasks, history, or message processing in web services.