← Back to all snippets
PYTHON

Implementing a Queue with `collections.deque`

Learn to implement an efficient, thread-safe queue (FIFO) in Python using `collections.deque` for fast appends and pops from both ends.

from collections import deque

# Create a deque to act as a queue (FIFO - First-In, First-Out)
queue = deque()

# Add elements to the right (enqueue)
queue.append("task1")
queue.append("task2")
queue.append("task3")
print(f"Queue after enqueuing: {list(queue)}")

# Remove elements from the left (dequeue)
first_task = queue.popleft()
print(f"Dequeued: {first_task}")
print(f"Queue after first dequeue: {list(queue)}")

second_task = queue.popleft()
print(f"Dequeued: {second_task}")
print(f"Queue after second dequeue: {list(queue)}")

# Add another element
queue.append("task4")
print(f"Queue after adding task4: {list(queue)}")

# Check the current front of the queue without removing
if queue:
    print(f"Next task in queue (peek): {queue[0]}")

# Clear the queue
queue.clear()
print(f"Queue after clear: {list(queue)}")
How it works: The `collections.deque` (double-ended queue) is a list-like container optimized for fast appends and pops from both ends. Unlike a standard list, which is inefficient for `pop(0)` operations (requiring all subsequent elements to shift), `deque` offers O(1) complexity for `append()`, `appendleft()`, `pop()`, and `popleft()`. This makes it ideal for implementing queues or other data structures requiring efficient additions and removals from either end.

Need help integrating this into your project?

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

Hire DigitalCodeLabs