PYTHON
Implementing a High-Performance Queue (FIFO) with collections.deque
Utilize Python's collections.deque for efficient queue implementations (FIFO), offering O(1) appends and pops from both ends, perfect for task queues and buffers.
from collections import deque
# Create a new deque (doubly-ended queue)
task_queue = deque()
# Enqueue elements (add to the right end)
task_queue.append('task_1')
task_queue.append('task_2')
task_queue.append('task_3')
print(f"Queue after enqueuing: {list(task_queue)}")
# Dequeue elements (remove from the left end)
next_task = task_queue.popleft()
print(f"Dequeued: {next_task}, Queue remaining: {list(task_queue)}")
next_task = task_queue.popleft()
print(f"Dequeued: {next_task}, Queue remaining: {list(task_queue)}")
# Check if queue is empty
if not task_queue:
print("Queue is empty.")
# Add more elements
task_queue.append('task_4')
task_queue.appendleft('urgent_task') # deque also supports adding to the left
print(f"Queue after more operations: {list(task_queue)}")
How it works: The `collections.deque` (double-ended queue) is a list-like container that supports fast appends and pops from both ends. Unlike regular Python lists, which have O(N) complexity for inserting or deleting from the beginning, `deque` offers O(1) performance for `append()`, `pop()`, `appendleft()`, and `popleft()`. This makes it the ideal data structure for implementing efficient queues (FIFO - First-In, First-Out) or stacks (LIFO - Last-In, First-Out) when performance at both ends is critical.