PYTHON

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

Utilize Python's `collections.deque` for an efficient and thread-safe queue implementation, optimizing append and pop operations from both ends, which is superior to lists for this use case.

from collections import deque

# Create a new deque (double-ended queue)
my_queue = deque()

# Add elements to the right (enqueue)
my_queue.append('Task 1')
my_queue.append('Task 2')
my_queue.append('Task 3')
print(f"Queue after appends: {my_queue}")

# Remove elements from the left (dequeue)
first_task = my_queue.popleft()
print(f"Processed task: {first_task}")
print(f"Queue after popleft: {my_queue}")

second_task = my_queue.popleft()
print(f"Processed task: {second_task}")
print(f"Queue after second popleft: {my_queue}")

# You can also append to the left or pop from the right
my_queue.appendleft('Urgent Task')
print(f"Queue after appendleft: {my_queue}")

last_task = my_queue.pop()
print(f"Popped from right: {last_task}")
print(f"Queue after pop (right): {my_queue}")
How it works: While standard Python lists can technically be used as queues, they are inefficient for operations that require removing elements from the beginning (`list.pop(0)`) because it involves shifting all subsequent elements. `collections.deque` (double-ended queue) is specifically designed for efficient appends and pops from both ends, achieving O(1) complexity for these operations. This makes `deque` the ideal data structure for implementing queues or stacks in Python, especially in scenarios where performance is critical or for multi-threaded applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs