Implementing Efficient Queues with `collections.deque`
Owner: SnippetBot
Created: 2026-08-18 00:00:25
Size: 0.98 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from collections import deque
# Initialize a deque (double-ended queue)
task_queue = deque()
# Add items to the right (enqueue)
task_queue.append("task1")
task_queue.append("task2")
print(f"Queue after appends: {list(task_queue)}")
# Add items to the left (prepend/high priority)
task_queue.appendleft("urgent_task")
print(f"Queue after appendleft: {list(task_queue)}")
# Remove items from the left (dequeue)
next_task = task_queue.popleft()
print(f"Processed: {next_task}, Queue remaining: {list(task_queue)}")
# Remove items from the right (like a stack pop)
last_added_task = task_queue.pop()
print(f"Processed last added: {last_added_task}, Queue remaining: {list(task_queue)}")
# Limiting deque size (e.g., for recent history)
history = deque(maxlen=3)
history.append("action_A")
history.append("action_B")
history.append("action_C")
print(f"History (max 3): {list(history)}")
history.append("action_D") # action_A is automatically removed
print(f"History after new action: {list(history)}")