Is it possible to examine items in a Queue
in Python without calling .get()
? As per the docs, indexing is not allowed in Queue. I need to check if the item at the head of the queue satisfies some condition and if it does, remove it from the queue. Similarly I need to check if any other item in the queue satisfy the similar condition and remove it.
Am I using the wrong data structure here?
To check if an element is in a queue in Python: Access the queue attribute on the queue to get a deque object. Use the in operator to check if the element is in the queue. The in operator tests for membership.
A peek function in the python queue is used to print the first element of the queue. It returns the item which is present at the front index of the queue. It will not remove the first element but print it. Let us construct a function inside the class queue to perform a peek operation.
Like stack, queue is a linear data structure that stores items in First In First Out (FIFO) manner. With a queue the least recently added item is removed first. A good example of queue is any queue of consumers for a resource where the consumer that came first is served first.
queue_object.queue will return copy of your queue in a deque object which you can then use the slices of. It is of course, not syncronized with the original queue, but will allow you to peek at the queue at the time of the copy.
There's a good rationalization for why you wouldn't want to do this explained in detail in this thread comp.lang.python - Queue peek?. But if you're just trying to understand how Queue works, this is one simple way.
import Queue q = Queue.Queue() q.push(1) q.put('foo') q.put('bar') d = q.queue print(d) deque(['foo', 'bar']) print(d[0]) 'foo'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With