1
a=[1,10]
b=[2,20]
h=[]
heapq.heappush(h,a)
heapq.heappush(h,b)
a[0]=5
heapq.heappop(h)

pops [5,10] instead of [2,20]

If I have used heapq.heapify(h) before popping up, it gives correct answer : i.e [2,20] Is it always required to heapify the list before popping in case you have changed any of the list values?

1 Answer 1

3

When using heapq, list.sort() or any other sorting module like sortedcontainers, modifying a mutable item such as a list will cause the internal sorting to be disrupted. Usage of tuples in that case is recommended as it will prevent accidental corruption of the sort.

When using heapq or bisect, the module thinks the list is already sorted and the algorithm used works only on sorted lists. Modifying the sorted list will break the algorithm and produce unexpected results.

If you change a mutable object, you must re-sort the list if you want it to function correctly. heapq.heapify() is indeed the way to sort it if you're using heapq.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.