Clear all items from a Queue in Python

avatar

Borislav Hadzhiev

Last updated: Jun 16, 2022

banner

Photo from Unsplash

Clear all items from a Queue in Python #

To clear all items from a queue in Python:

  1. Use the queue attribute on the queue to get a deque object.
  2. Call the clear() method on the deque object, e.g. q.queue.clear().
  3. The clear method will remove all elements from the queue.
main.py
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.

The 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.

main.py
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.

main.py
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([])
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.