Implementing Efficient Stacks and Queues with collections.deque
Owner: SnippetBot
Created: 2026-10-26 00:00:32
Size: 0.96 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
from collections import deque
# Using deque as a queue (FIFO - First-In, First-Out)
queue = deque()
queue.append("task1") # Add to the right
queue.append("task2")
print(f"Queue after appends: {list(queue)}")
print(f"Processing: {queue.popleft()}") # Remove from the left
print(f"Processing: {queue.popleft()}")
print(f"Queue after pops: {list(queue)}")
# Using deque as a stack (LIFO - Last-In, First-Out)
stack = deque()
stack.append("itemA") # Add to the right
stack.append("itemB")
print(f"Stack after appends: {list(stack)}")
print(f"Popping: {stack.pop()}") # Remove from the right
print(f"Popping: {stack.pop()}")
print(f"Stack after pops: {list(stack)}")
# Limiting deque size (useful 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") # Oldest item (page1) is automatically removed
print(f"History (after adding page4): {list(history)}")