1

I want to know what the most recently enqueued item is in a queue. how do I find this out?

In other words, how to find the last item that a queue will dequeue ( or the most recently enqueued item)

Rahul Sharma
  • 1,117
  • 3
  • 10
  • 12

2 Answers2

1

Im not entirely sure what you are trying to achieve here, but the following might work, just check that the queue is not empty.

>>> from Queue import Queue
>>> q = Queue()    
>>> _ = [q.put(index) for index in xrange(2, 10)]
>>> if not q.empty():
...    q.queue[-1]
9
>>> 

Im assuming that you are using python's own Queue object, which I would recommend since its thread safe :)

Samy Vilar
  • 10,800
  • 2
  • 39
  • 34
0

How are you implementing your queue? If it's implemented as a list, then presumably yourdata.pop(0) would remove and return the first item. The most recently enqueued item would be at the end of the list, yourdata.pop() to remove and return, or yourdata[-1] to view the item without modifying the list contents.

Using a list for a queue is a bad idea because you incur a performance penalty, however: every time the first item gets removed, all subsequent items in the list would have to be updated. You'll get better performance from a specialized queue implementation such as collections.deque. See discussion at: http://docs.python.org/tutorial/datastructures.html#using-lists-as-queues

For information on Queue vs deque in python, see: Queue.Queue vs. collections.deque

Community
  • 1
  • 1
abought
  • 2,652
  • 1
  • 18
  • 13