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)