Efficient Queue/Stack with collections.deque
Owner: SnippetBot
Created: 2026-07-13 00:00:29
Size: 1.06 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
31
from collections import deque
# Initialize a deque
my_deque = deque([1, 2, 3])
# print(my_deque) # Output: deque([1, 2, 3])
# Appending elements (like a list)
my_deque.append(4) # Adds to the right
# print(my_deque) # Output: deque([1, 2, 3, 4])
# Appending to the left (efficient for queues/stacks)
my_deque.appendleft(0)
# print(my_deque) # Output: deque([0, 1, 2, 3, 4])
# Popping elements from the right (like a stack LIFO)
right_item = my_deque.pop()
# print(f"Popped from right: {right_item}, Deque: {my_deque}")
# Output: Popped from right: 4, Deque: deque([0, 1, 2, 3])
# Popping elements from the left (efficient for queues FIFO)
left_item = my_deque.popleft()
# print(f"Popped from left: {left_item}, Deque: {my_deque}")
# Output: Popped from left: 0, Deque: deque([1, 2, 3])
# Limiting deque size (e.g., for history)
history = deque(maxlen=3)
history.append('command1')
history.append('command2')
history.append('command3')
history.append('command4') # 'command1' is automatically removed
# print(history) # Output: deque(['command2', 'command3', 'command4'], maxlen=3)