← Back to Python

All Topics

Advertisement

Learn/Python/Advanced Python

Queues and Deques

Topic: Data Structures

Advertisement

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

  1. Implement breadth-first search with deque
  2. Create fixed-size cache with deque
  3. Use PriorityQueue for task scheduling
  4. Implement sliding window with deque
  5. Build producer-consumer with Queue

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →