---
title: "heap"
url: https://perrotta.dev/2026/01/heap/
last_updated: 2026-01-11
---


```python
import heapq
# note: NOT from collections import heapq
# mnemonic: "heap priority queue -> heap pq"

pq = [3, 2, 1, 5]
assert heapq.heapify(pq) is None
assert pq == [1, 2, 3, 5]

assert heapq.heappop(pq) == 1 # min heap!
assert heapq.heappop(pq) == 2 # min heap!

pq = [3, 2, 1, 5]
pq = [-num for num in pq]
assert heapq.heapify(pq) is None
assert -heapq.heappop(pq) == 5 # max heap trick
assert -heapq.heappop(pq) == 3 # max heap trick

# built heap from scratch
pq = []
for num in range(5):
    heapq.heappush(pq, num)
assert heapq.heappop(pq) == 0

assert heapq.heappushpop(pq, 6) == 1
assert heapq.heappop(pq) == 2

pq = []
for num in range(5):
    heapq.heappush(pq, num)
assert heapq.heappop(pq) == 0

# heappoppush, essentially – why did they name it as heapreplace?
assert heapq.heapreplace(pq, -1) == 1

assert heapq.nlargest(2, pq) == [4, 3]
assert heapq.nsmallest(2, pq) == [-1, 2]

assert pq[0] == -1  # .peek() essentially
```

