PYTHON

Efficiently Managing Queues with `collections.deque`

Learn how to use Python's `collections.deque` for fast appends and pops from both ends, ideal for managing queues, history, or message buffers in web applications.

from collections import deque

# Create a new deque
request_queue = deque()

# Add items to the right (end) of the queue
request_queue.append('user_login_request_1')
request_queue.append('product_view_request_2')

# Add items to the left (front) of the queue
request_queue.appendleft('priority_admin_task_0')

# The queue now is: deque(['priority_admin_task_0', 'user_login_request_1', 'product_view_request_2'])

# Process items from the left (front) - typically for queues
next_request = request_queue.popleft()
print(f"Processed: {next_request}") # Output: Processed: priority_admin_task_0

# Add and remove with a fixed maximum length (e.g., recent history)
history = deque(maxlen=3)
history.append('page_A')
history.append('page_B')
history.append('page_C')
print(f"Current history: {history}") # Output: Current history: deque(['page_A', 'page_B', 'page_C'])
history.append('page_D') # 'page_A' is automatically removed
print(f"Updated history: {history}") # Output: Updated history: deque(['page_B', 'page_C', 'page_D'])

# Extending a deque with multiple items
request_queue.extend(['analytics_event_3', 'logout_request_4'])
print(f"Extended queue: {request_queue}")
How it works: The `collections.deque` (double-ended queue) is a list-like container offering O(1) (constant time) performance for appends and pops from both ends. Unlike standard Python lists where insertions/deletions at the beginning can be O(n), `deque` is highly efficient for managing queues (FIFO - First-In, First-Out) or even stacks (LIFO - Last-In, First-Out) if only one end is used consistently. It's particularly useful in web applications for managing recent activity feeds, request queues, or maintaining a limited history of operations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs