PYTHON
Implement a High-Performance Queue (FIFO) in Python
Learn to use collections.deque for creating efficient First-In, First-Out (FIFO) queues in Python, optimized for fast appends and pops from both ends.
from collections import deque
# Create a new deque object
queue = deque()
print(f"Initial queue: {list(queue)}")
# Add elements to the right (enqueue operation)
queue.append('Task 1')
queue.append('Task 2')
queue.append('Task 3')
print(f"Queue after enqueuing: {list(queue)}")
# Remove elements from the left (dequeue operation)
first_task = queue.popleft()
print(f"Dequeued: {first_task}")
print(f"Queue after dequeuing: {list(queue)}")
# demonstrate adding to the left (LIFO stack push)
queue.appendleft('Task 0 (High Priority)')
print(f"Queue after appendleft: {list(queue)}")
# demonstrate removing from the right (LIFO stack pop)
last_item = queue.pop()
print(f"Popped from right: {last_item}")
print(f"Queue after pop (from right): {list(queue)}")
How it works: A queue is a linear data structure that follows the First-In, First-Out (FIFO) principle. Python's `collections.deque` (double-ended queue) is the ideal data structure for implementing efficient queues. Unlike regular lists, which can be slow for removals from the beginning, `deque` provides O(1) (constant time) performance for appending and popping elements from both ends, making it perfect for managing task queues, buffers, and other FIFO scenarios.