PYTHON

Implement a High-Performance Queue (FIFO)

Learn to implement an efficient First-In, First-Out (FIFO) queue in Python using `collections.deque`, ideal for tasks requiring fast appends and pops from both ends.

from collections import deque

# Create a new deque to act as a queue
my_queue = deque()

# Enqueue elements (add to the right)
my_queue.append("Task A")
my_queue.append("Task B")
my_queue.append("Task C")
print(f"Queue after enqueuing: {my_queue}")

# Dequeue elements (remove from the left)
processed_task1 = my_queue.popleft()
processed_task2 = my_queue.popleft()
print(f"Processed: {processed_task1}, {processed_task2}")
print(f"Queue after dequeuing: {my_queue}")

# Check if queue is empty
if not my_queue:
    print("Queue is empty!")
else:
    print(f"Next task: {my_queue[0]}")

my_queue.popleft() # Process the last item
print(f"Queue after final dequeuing: {my_queue}")
How it works: This snippet illustrates how to implement a high-performance First-In, First-Out (FIFO) queue using Python's `collections.deque`. A `deque` (double-ended queue) supports O(1) time complexity for appending and popping elements from both ends, making it significantly more efficient than a standard `list` for queue operations where elements are frequently added to one end and removed from the other. Elements are added to the right using `append()` (enqueue) and removed from the left using `popleft()` (dequeue), adhering to the FIFO principle.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs