Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python heapq max-heap: keep highest-priority scores at the root

Last updated: 1 Oct 20265 min read
tutorial
IntermediateBy AITrove Editorial

The max-heap functions avoid sign inversion when numeric priority itself is the ordering key.

Download Python source kit

Operation contract

Four inspection scores are heapified and consumed from highest to lowest. The heap is a list, but its internal list order is not a sorted report; only repeated heappop_max calls establish descending output. The score represents urgency, not an object with tie-breaking metadata.

Failure boundary

If work items carry payloads, define an explicit tie-break rule so equal priorities do not compare incompatible objects. Changing an item's priority in place breaks the heap invariant. A heap gives fast access to one extreme, not constant-time arbitrary deletion or a fully sorted index.

Working program

python
from heapq import heapify_max, heappop_max, heappush_max

inspection_scores = [47, 82, 65]
heapify_max(inspection_scores)
heappush_max(inspection_scores, 91)
descending = []
while inspection_scores:
    descending.append(heappop_max(inspection_scores))
print("priority_order", descending)

Output

Output
priority_order [91, 82, 65, 47]

Costs and limits

Heap construction is O(n), each push or pop is O(log n), and popping all items is O(n log n). The heap stores O(n) values.

Common Mistakes

  • The backing list is not a sorted sequence.
  • Do not mutate a queued priority without restoring the heap invariant.
  • Tie-breaking must be defined before storing payload records.

Connected lessons

Test this contract.

python
heapq-native-maxheap
Storage details