You write a Python script that processes tasks from a list. It works fine — until you add threading. Two threads check the list at the same moment and race for the same work. One crashes with IndexError because, by the time it pops, the list is empty. The problem: a Python list is not thread-safe, and it has no built-in way to block consumers when there is nothing to process. Python’s queue module fixes both problems. Here is how to use it.
In this tutorial, you will learn to:
- Understand what queues are and why lists fail as task queues
- Use
queue.Queuefor thread-safe producer-consumer patterns - Use
collections.dequefor fast append and pop from both ends - Choose between FIFO, LIFO, and priority queue behaviors
- Avoid the most common queue pitfalls in production code
Page Contents
Prerequisites
This tutorial assumes you are comfortable with Python lists and basic Python syntax including import statements. Familiarity with threads is helpful but not required — queue.Queue handles the thread-safety details for you.
What Is a Queue?
A queue is an ordered collection of items where the first item added is the first item removed — First In, First Out (FIFO). Think of a queue at a coffee shop: the first person in line gets served first. In programming, queues are used to coordinate work between producers (tasks are added) and consumers (tasks are removed and processed).
Python gives you two main queue implementations:
queue.Queue— thread-safe, designed for communication between threads. Blocks consumers when the queue is empty.collections.deque— fast, general-purpose double-ended queue. Individual appends and pops are atomic, but compound operations are not thread-safe; much faster thanqueue.Queuefor single-threaded use.
Why Not Just Use a List?
You might wonder: why not just use a Python list to manage tasks? The answer depends on what you are building. A list works fine for a single-threaded script, but it has three critical limitations when used as a task queue:
- Not thread-safe for compound operations — a check-then-pop sequence such as
if tasks: tasks.pop(0)raisesIndexErrorwhen another thread empties the list in between - No blocking on empty — calling
list.pop(0)on an empty list raisesIndexErrorinstead of waiting - Slow at scale —
list.pop(0)is O(n) because every element must shift left
Python’s queue.Queue solves all three: it is thread-safe, it blocks consumers until data is available, and it is optimized for enqueue and dequeue operations.
queue.Queue: Thread-Safe Task Queues
queue.Queue is built for coordinating work between threads. It handles all the locking internally, so you do not need to manage synchronization yourself.
Basic Operations: put() and get()
import queue
# Create a queue with a maximum size of 3
task_queue = queue.Queue(maxsize=3)
# put() adds an item — blocks if queue is full
task_queue.put("task_1")
task_queue.put("task_2")
task_queue.put("task_3")
print(task_queue.full()) # True
print(task_queue.qsize()) # 3
# get() removes and returns the oldest item — blocks if empty
item = task_queue.get()
print(item) # task_1
print(task_queue.qsize()) # 2
# Drain the two remaining items, then get_nowait() raises queue.Empty
task_queue.get_nowait() # task_2
task_queue.get_nowait() # task_3
try:
task_queue.get_nowait()
except queue.Empty:
print("Queue is empty — nothing to get")
Blocking Behavior — Waiting for Data
One of the most useful features of queue.Queue is that get() blocks the calling thread until an item is available. This is perfect for a consumer loop — you do not need to poll or sleep.
import queue
q = queue.Queue()
# Consumer: blocks until an item arrives
print("Waiting for an item...")
item = q.get() # This blocks until q.put() is called
print(f"Got: {item}")
Note:
put()also blocks when the queue is full. Usemaxsizeto set a bound, andput_nowait()/get_nowait()for non-blocking alternatives that raisequeue.Fullorqueue.Empty.
Producer-Consumer Pattern with Queue
Here is a complete producer-consumer example using queue.Queue with two threads. The producer generates tasks; the consumer processes them. The queue handles all thread coordination safely.
import queue
import threading
task_queue = queue.Queue()
def producer():
"""Simulate a producer that adds 5 tasks to the queue."""
for i in range(1, 6):
task_queue.put(f"task_{i}")
print(f"Producer added: task_{i}")
def consumer():
"""Simulate a consumer that processes tasks until queue is empty."""
while True:
try:
task = task_queue.get(timeout=2) # Wait up to 2 seconds
print(f"Consumer processed: {task}")
task_queue.task_done()
except queue.Empty:
print("Consumer: no more tasks — exiting")
break
# Start consumer first (it will block on get())
consumer_thread = threading.Thread(target=consumer, daemon=True)
consumer_thread.start()
# Producer adds tasks
producer()
# Wait for all tasks to be processed
task_queue.join()
print("All tasks processed.")
collections.deque: Fast General-Purpose Queues
collections.deque (double-ended queue) is the right choice for single-threaded code that needs fast append and pop from both ends. It is significantly faster than queue.Queue because it does not pay the cost of thread-safe locking.
from collections import deque
# Create a deque — acts as a FIFO queue by default
dq = deque()
# append() adds to the right (back)
dq.append("first")
dq.append("second")
dq.append("third")
# popleft() removes from the left (front) — O(1), fast!
print(dq.popleft()) # first — O(1)
print(dq.popleft()) # second — O(1)
print(dq) # deque(['third'])
# appendleft() adds to the front
dq.appendleft("new_first")
print(dq) # deque(['new_first', 'third'])
Note:
collections.dequemakes individualappend()andpopleft()calls atomic, but compound operations are not thread-safe: a check-then-pop such asif dq: dq.popleft()can race. If threads coordinate through it, add your own locking. For multi-threaded producer-consumer code, usequeue.Queueinstead.
Queue Types: FIFO, LIFO, and Priority
Python’s queue module gives you three queue classes, each with different removal order:
| Queue Class | Order | Use Case |
|---|---|---|
queue.Queue | FIFO (oldest first) | Task queues, producer-consumer |
queue.LifoQueue | LIFO (newest first) | Task stacks, undo/redo |
queue.PriorityQueue | Lowest value first | Job scheduling, event processing |
PriorityQueue — Tasks With Urgency Levels
queue.PriorityQueue always removes the item with the lowest value first. A common pattern is to store tuples of (priority, data) — lower priority numbers come out first. If you want to know how the heap underneath actually works, see Python Heap and Priority Queue.
import queue
# (priority, task) — lower number = higher priority
pq = queue.PriorityQueue()
pq.put((2, "send email report")) # low priority
pq.put((1, "process payment")) # high priority
pq.put((3, "cleanup temp files")) # very low priority
# Highest priority (lowest number) comes out first
while not pq.empty():
priority, task = pq.get()
print(f"[Priority {priority}] {task}")
# Output:
# [Priority 1] process payment
# [Priority 2] send email report
# [Priority 3] cleanup temp files
LifoQueue — A Task Stack
queue.LifoQueue works like a stack — the last item added is the first removed. This is useful for implementing undo functionality or depth-first traversal patterns.
import queue
stack = queue.LifoQueue()
stack.put("step_1")
stack.put("step_2")
stack.put("step_3")
# Most recent item comes out first
while not stack.empty():
print(stack.get())
# Output:
# step_3
# step_2
# step_1
Practical Example: BFS Using a Queue
Queues are fundamental to breadth-first search (BFS) algorithms. BFS explores a graph level by level — a queue makes this natural. Level Order Tree Traversal is a common BFS application used in coding interviews.
from collections import deque
def bfs_traverse(graph, start):
"""
Breadth-first search using a deque as the queue.
graph: dict mapping each node to its neighbors
start: starting node
"""
visited = set()
q = deque([start])
visited.add(start)
while q:
node = q.popleft() # Dequeue from front — O(1)
print(f"Visiting: {node}")
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
q.append(neighbor) # Enqueue from back
# Example: graph represented as adjacency list
graph = {
"A": ["B", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F"],
"D": ["B"],
"E": ["B", "F"],
"F": ["C", "E"]
}
bfs_traverse(graph, "A")
# Output order (BFS level by level):
# Visiting: A
# Visiting: B
# Visiting: C
# Visiting: D
# Visiting: E
# Visiting: F
Common Mistakes / Gotchas
- Confusing
queue.Queuewithcollections.deque—Queueis thread-safe and blocks.dequeis faster but not thread-safe. Choose based on whether you have multiple threads. - Forgetting to call
task_done()—Queue.join()blocks until everyget()is matched by atask_done(). Forgetting it causesjoin()to hang forever. - Using
get()without a timeout in a daemon thread — if the producer never adds an item, the consumer blocks forever and never processes anything. Always use a timeout or a sentinel value. - Blocking forever with
get()— if noput()ever happens,get()waits indefinitely. Useget(timeout=N)and catchqueue.Emptywhen timeouts are possible. - PriorityQueue with non-comparable items —
PriorityQueuecallsheapq.heappushinternally. If items are not comparable (e.g., custom objects), it raisesTypeError. Always use tuples like(priority, data).
Summary & Next Steps
Python queues come in two main flavors: queue.Queue for thread-safe producer-consumer patterns across threads, and collections.deque for fast single-threaded FIFO/LIFO operations. Both are far superior to using a raw list as a queue — lists are not thread-safe, they do not block on empty, and list.pop(0) is O(n) slow.
Now that you understand queues, you can explore how they power algorithms and real systems:
- Level Order Tree Traversal — BFS uses queues to visit tree nodes level by level
- Python Lists for Beginners — understand the data structure queues are often compared to
- Python Learning Path — structured guide from beginner to advanced
- Official Python queue module documentation
- collections.deque documentation (docs.python.org)
- heapq module — used by PriorityQueue (docs.python.org)
Frequently Asked Questions
What is the difference between queue.Queue and collections.deque in Python?
queue.Queue is thread-safe and blocks consumers when the queue is empty — ideal for multi-threaded producer-consumer code. collections.deque is not thread-safe but is significantly faster for single-threaded use, and both append() and popleft() are O(1). Use Queue when threads share a queue; use deque for single-threaded FIFO/LIFO needs.
How do I choose between FIFO, LIFO, and Priority queues in Python?
Use FIFO (queue.Queue) when tasks must be processed in the order they arrive — standard task queues. Use LIFO (queue.LifoQueue) when you need a stack — for undo/redo features or depth-first traversal. Use Priority (queue.PriorityQueue) when some tasks are more urgent — pass (priority, task) tuples where lower numbers have higher priority.
Why does queue.Queue.get() block forever?
get() blocks indefinitely until an item is available. If no item is ever added, the calling thread hangs forever. Always use get(timeout=N) when the producer might not send data, and catch queue.Empty to handle the timeout gracefully.
Is collections.deque thread-safe?
Not for coordinated access. collections.deque makes individual append() and popleft() calls atomic, so one thread appending while another pops will not corrupt the deque, but multi-step logic such as if dq: dq.popleft() can race, and iterating while another thread mutates is unsafe. For a shared queue, use queue.Queue; for a shared deque, add a threading.Lock. See the official deque documentation for details.

