To remove all items from a Queue in Python, use the queue.clear() method. Below is an example:
Remove all items from a Queue in Python
To remove all items from a queue in Python:
- To obtain a deque object, simply use the queue's
queue
attribute. - Use
q.queue.clear
to invoke theclear()
method on a dequeobject ()
. - If you use
clear
on a queue, it will clear out everything in it.
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([])
Deque objects, which are referenced by the queue
attribute, feature a clear
method.
The clear()
function empties the deque of all of its elements, leaving it with a length of 0.
Use a mutex
lock to prevent incompatible threads from modifying the operation at the same time.
import queue q = queue.Queue() for item in range(10): q.put(item) print(q.queue) # mutex lock with q.mutex: q.queue.clear() print(q.queue)
If your code operates in a multi-threaded setting, you can employ the use of a mutex
lock.
The second option is to make a new queue and remove 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)