Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

examining items in a python Queue

Tags:

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?

like image 340
damon Avatar asked May 22 '13 07:05

damon


People also ask

How do I see queue items in Python?

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.

Can you peek in a queue Python?

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.

What does queue () do in Python?

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.


1 Answers

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' 
like image 194
synthesizerpatel Avatar answered Sep 21 '22 21:09

synthesizerpatel