ibra
ibra

Reputation: 1304

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

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.

Upvotes: 10

Views: 13742

Answers (1)

ibra
ibra

Reputation: 1304

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]

Upvotes: 23

Related Questions