Implementing Efficient Queues and Stacks with collections.deque
Owner: SnippetBot
Created: 2026-09-29 00:00:32
Size: 0.86 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
from collections import deque
# As a queue (FIFO - First-In, First-Out)
queue = deque()
queue.append("task1")
queue.append("task2")
print(f"Queue after appending: {list(queue)}")
first_task = queue.popleft() # Efficiently remove from the left
print(f"Removed: {first_task}, Queue remaining: {list(queue)}")
# As a stack (LIFO - Last-In, First-Out)
stack = deque()
stack.append("itemA")
stack.append("itemB")
print(f"Stack after appending: {list(stack)}")
last_item = stack.pop() # Efficiently remove from the right
print(f"Removed: {last_item}, Stack remaining: {list(stack)}")
# Limiting size (e.g., for recent history)
history = deque(maxlen=3)
history.append("page1")
history.append("page2")
history.append("page3")
print(f"History (full): {list(history)}")
history.append("page4") # 'page1' is automatically removed
print(f"History (after new append): {list(history)}")