heappushpop Differs From heapreplace on Top-K
Contrast heapq.heappushpop and heapq.heapreplace in fixed-size top-k buffers: heappushpop keeps out smaller items, while heapreplace always pops first.
Code
import heapq
# Keep the top-3 highest latencies without sorting the full stream
def track_top3(samples: list[int]) -> list[int]:
top = []
for value in samples:
if len(top) < 3:
heapq.heappush(top, value)
else:
# heappushpop checks the incoming item before discarding the smallest
heapq.heappushpop(top, value)
return sorted(top, reverse=True)
stream = [18, 92, 41, 7, 130, 64, 15, 110]
print("top-3 latencies:", track_top3(stream))
# Contrast: heapreplace pops the root BEFORE pushing the new element
h_pushpop = [10, 30, 50]
h_replace = [10, 30, 50]
out_a = heapq.heappushpop(h_pushpop, 5)
out_b = heapq.heapreplace(h_replace, 5)
print("heappushpop(5): popped=", out_a, "heap=", sorted(h_pushpop))
print("heapreplace(5): popped=", out_b, "heap=", sorted(h_replace))Output
Captured from a sandboxed run of this snippet in the build pipeline.
top-3 latencies: [130, 110, 92]
heappushpop(5): popped= 5 heap= [10, 30, 50]
heapreplace(5): popped= 10 heap= [5, 30, 50]Logic trace — heappushpop Differs From heapreplace on Top-K
Program behavior centers entirely within callable track_top3 — everything else is wiring.
The loop for value in samples is the only repeated construct.
Watch out for
- Runs on the standard library alone; nothing to install.
Putting it to use
Entry signature: def track_top3(samples: list[int]) -> list[int]
The run prints top-3 latencies:, heappushpop(5): popped=, heapreplace(5): popped= — each prefix names the step that produced it.
Treat track_top3 as the API: import it, and ignore the supporting code.
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `track_top3` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.