Search code examples
pythonqueuepriority-queue

check if element exists in priorityQueue of tuples


Say I have this code:

q = PriorityQueue()
a = ((1,1), 10, 0)
b = ((2,2), 99, 200)
q.put(a)
q.put(b)

I'd like to check if the element (1, 1) exists in any of the tuples in the queue. Is there a way to do this?


Solution

  • A PriorityQueue object stores its items in a list accessible via the queue attribute. Thus, you can do:

    >>> q = PriorityQueue()
    >>> a = ((1, 1), 10, 0)
    >>> q.put(a)
    >>> any((1, 1) in item for item in q.queue)
    True
    

    This is, of course, an O(N) operation with N being the number of elements in the priority queue.