PYTHON
Efficient Queue and Stack Operations with Deque
Learn how to use Python's collections.deque for optimized queue (FIFO) and stack (LIFO) operations, supporting fast appends and pops from both ends.
from collections import deque
# As a queue (FIFO)
q = deque()
q.append("task1")
q.append("task2")
print(f"Queue after append: {list(q)}")
print(f"Processing: {q.popleft()}")
print(f"Queue after popleft: {list(q)}")
# As a stack (LIFO)
s = deque()
s.append("itemA")
s.append("itemB")
print(f"Stack after append: {list(s)}")
print(f"Popping: {s.pop()}")
print(f"Stack after pop: {list(s)}")
# Fixed-size history
history = deque(maxlen=3)
history.append("page1")
history.append("page2")
history.append("page3")
history.append("page4") # page1 is automatically removed
print(f"Fixed-size history: {list(history)}")
How it works: collections.deque (double-ended queue) is a list-like container offering O(1) time complexity for appending and popping elements from both ends, unlike standard Python lists which are slow for pop(0). It's ideal for implementing efficient queues, stacks, or managing fixed-size collections like recent history in web applications.