PYTHON

Implement a High-Performance Queue with `collections.deque`

Discover how to use Python's `collections.deque` to create efficient, thread-safe queues (FIFO) or stacks (LIFO), ideal for task processing and managing sequences.

from collections import deque

# Initialize a deque to act as a queue (FIFO)
task_queue = deque()

# Add items to the queue (enqueue)
task_queue.append("task_A")
task_queue.append("task_B")
task_queue.append("task_C")

print(f"Queue after adding items: {list(task_queue)}")

# Process items from the front of the queue (dequeue)
processed_task_1 = task_queue.popleft()
processed_task_2 = task_queue.popleft()

print(f"Processed task 1: {processed_task_1}")
print(f"Processed task 2: {processed_task_2}")
print(f"Queue after processing: {list(task_queue)}")

# `deque` can also be used as a stack (LIFO)
# stack = deque()
# stack.append("item1")
# stack.append("item2")
# popped_item = stack.pop() # Pops from the right (end)
How it works: The `collections.deque` (double-ended queue) is a list-like container offering O(1) performance for appending and popping elements from either end. This snippet shows its use as a FIFO (First-In, First-Out) queue, where `append()` adds to the right and `popleft()` removes from the left. This makes it highly efficient for managing task queues or event logs in web applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs