9

How to access the top element in heapq without deleting (popping) it python ?
I need only to check the element at the top of my heapq without popping it. How can I do that.

1 Answer 1

22

From docs python, under heapq.heappop definition, it says:

To access the smallest item without popping it, use heap[0].

It says smallest, because it is a min heap. So the item at the top will be the smallest one.

Illustration:

import heapq

pq = []

heapq.heappush(pq,5)
heapq.heappush(pq,3)
heapq.heappush(pq,1)
heapq.heappush(pq,2)
heapq.heappush(pq,4)

print("element at top = ",pq[0])
print("check the heapq : ", pq)

Result:

element at top =  1                                                                                        
check the heapq :  [1, 2, 3, 5, 4]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.