PYTHON
Build an Efficient FIFO Queue with Python's Deque
Learn to create a fast First-In, First-Out (FIFO) queue using collections.deque in Python, perfect for managing tasks, messages, or processing order in web applications.
from collections import deque
# Initialize a deque to act as a FIFO queue
task_queue = deque()
# Enqueue elements (add to the right end)
print("Enqueuing tasks...")
task_queue.append("Task A: Process user signup")
task_queue.append("Task B: Send welcome email")
task_queue.append("Task C: Update user profile")
print(f"Queue after enqueuing: {list(task_queue)}")
# Dequeue elements (remove from the left end)
print("
Dequeuing tasks...")
if task_queue:
current_task = task_queue.popleft()
print(f"Processing: {current_task}")
if task_queue:
current_task = task_queue.popleft()
print(f"Processing: {current_task}")
print(f"Queue after dequeuing: {list(task_queue)}")
# Check if queue is empty
print(f"Is queue empty? {not bool(task_queue)}")
# Add more items
task_queue.append("Task D: Generate report")
print(f"Queue after adding more: {list(task_queue)}")
How it works: A `collections.deque` (double-ended queue) is a list-like container optimized for fast appends and pops from both ends. This makes it ideal for implementing queues (FIFO - First-In, First-Out) where elements are added to one end (`append()`) and removed from the other (`popleft()`). Unlike standard Python lists, `deque` operations at either end have O(1) performance, making it much more efficient for queue-like behavior when dealing with large datasets or managing asynchronous tasks in web services.