Introduction
Python provides specialized queue types for efficient insertion and removal from both ends.
Using deque
from collections import deque
dq = deque([1, 2, 3])
dq.append(4) # Right side: [1,2,3,4]
dq.appendleft(0) # Left side: [0,1,2,3,4]
dq.pop() # Remove right: returns 4
dq.popleft() # Remove left: returns 0
dq.rotate(1) # Rotate right by 1
dq.extend([5,6]) # Add multiple to right
Thread-Safe Queue
from queue import Queue, PriorityQueue, LifoQueue
# FIFO Queue
q = Queue()
q.put(item)
item = q.get()
# LIFO Queue (Stack)
stack = LifoQueue()
stack.put(1)
stack.put(2)
stack.get() # Returns 2
# Priority Queue
pq = PriorityQueue()
pq.put((1, "high"))
pq.put((3, "low"))
pq.put((2, "medium"))
pq.get() # Returns (1, "high")
Bounded Queue
from queue import Queue
bq = Queue(maxsize=3)
bq.put("a")
bq.put("b")
bq.full() # False
bq.put("c", timeout=1) # Block if full
Practice Problems
- Implement breadth-first search with deque
- Create fixed-size cache with deque
- Use PriorityQueue for task scheduling
- Implement sliding window with deque
- Build producer-consumer with Queue