Borislav Hadzhiev
Thu Jun 16 2022·1 min read
Photo by Sandra Seitamaa
To clear all items from a queue in Python:
queue
attribute on the queue to get a deque
object.clear()
method on the deque
object, e.g. q.queue.clear()
.clear
method will remove all elements from the queue.import queue q = queue.Queue() for item in range(10): q.put(item) print(q.queue) # 👉️ deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) q.queue.clear() print(q.queue) # 👉️ deque([])
The queue
attribute points to a deque
object, and deque
objects implement
a
clear
method.
clear()
method removes all elements from the deque and leaves it with a length of 0
.If you need to make the operation thread safe, use a mutex
lock.
import queue q = queue.Queue() for item in range(10): q.put(item) print(q.queue) # 👉️ deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # 👇️ use mutex lock with q.mutex: q.queue.clear() print(q.queue) # 👉️ deque([])
You can use a mutex
lock if your code runs in a multithreaded environment.
An alternative is to simply create a new queue and delete the old one.
import queue q = queue.Queue() for item in range(10): q.put(item) del q # 👈️ delete old queue new_q = queue.Queue() print(new_q.queue) # 👉️ deque([])