← Back to all snippets
PYTHON

Implementing a Fast Queue with Deque

Learn to use Python's collections.deque for high-performance queues and stacks, ideal for handling message streams or recent activity logs efficiently in web applications.

from collections import deque

# Initialize a deque
q = deque()

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

# Remove elements from the left (dequeue)
first_task = q.popleft()
print(f"Dequeued: {first_task}, Queue remaining: {list(q)}")

# Add elements to the left (stack push)
q.appendleft('urgent_task')
print(f"Queue after appendleft: {list(q)}")

# Remove elements from the right (stack pop)
last_task = q.pop()
print(f"Popped from right: {last_task}, Queue remaining: {list(q)}")

# Limit queue size (e.g., for a fixed-size log)
fixed_size_log = deque(maxlen=3)
fixed_size_log.append('log1')
fixed_size_log.append('log2')
fixed_size_log.append('log3')
fixed_size_log.append('log4') # 'log1' is automatically removed
print(f"Fixed-size log: {list(fixed_size_log)}")
How it works: collections.deque (double-ended queue) provides O(1) performance for appending and popping elements from both ends, unlike lists which are O(N) for insertions/deletions at the beginning. It's perfect for implementing efficient queues, stacks, or fixed-size circular buffers, commonly used in web applications for task management, request logging, or real-time data streams where fast head/tail operations are critical.

Need help integrating this into your project?

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

Hire DigitalCodeLabs