← Back to all snippets
PYTHON

Implement a High-Performance Queue (FIFO) with `collections.deque`

Discover how to create efficient queues for FIFO operations using Python's `collections.deque`, offering O(1) append and pop from both ends for speed.

from collections import deque

# Create a new deque
task_queue = deque()

# Add items to the right (enqueue)
task_queue.append("task_A")
task_queue.append("task_B")
task_queue.append("task_C")
# Deque content: deque(['task_A', 'task_B', 'task_C'])

# Process items from the left (dequeue)
if task_queue:
    next_task = task_queue.popleft() # Removes and returns 'task_A'
    # Deque content: deque(['task_B', 'task_C'])

if task_queue:
    another_task = task_queue.popleft() # Removes and returns 'task_B'
    # Deque content: deque(['task_C'])

# Check if the queue is empty
is_empty = not task_queue # True after popping all items
# Deque content: deque([])

# You can also set a maximum length for a deque
limited_history = deque(maxlen=3)
limited_history.append(1) # deque([1])
limited_history.append(2) # deque([1, 2])
limited_history.append(3) # deque([1, 2, 3])
limited_history.append(4) # deque([2, 3, 4]) (1 is automatically dropped)
How it works: `collections.deque` (double-ended queue) is ideal for implementing queues (FIFO - First-In, First-Out) and stacks (LIFO - Last-In, First-Out). It provides O(1) time complexity for appending and popping elements from both ends, making it significantly faster and more memory-efficient than lists for these operations, especially with large collections.

Need help integrating this into your project?

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

Hire DigitalCodeLabs