How to access the top element in heapq without deleting (popping) it python?

10.4k views Asked by At

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

There are 1 answers

0
ibra On BEST ANSWER

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]