On this page
heapq.heappushpop
Prev: heapq.heappush_max | Up: heapq | Next: heapq.heappushpop_max
Rel: heapq.heapify, heapq.heapify_max, heapq.heappop, heapq.heappop_max
Ref: docs.python.org — heapq.heappushpop
Tags: #public #python3 #stdlib #heapq
Import
import heapq
from heapq import heappushpop
Signature & Overview
heapq.heappushpop(heap, item, /)
Push item on the heap, then pop and return the smallest item from the heap.
Usage
import heapq
h = [2, 5, 8]
heapq.heapify(h)
assert heapq.heappushpop(h, 1) == 1 # pushed 1 is immediately popped
assert heapq.heappushpop(h, 4) == 2 # pops 2, keeps 4
Gotchas
- Faster than
heappush()followed byheappop(): Great for maintaining a fixed-size top-$k$ heap.
REPL Inspect
from heapq import heappushpop
help(heappushpop)
Linked from
Related notes
- tuts/python3/stdlib_module/heapq/heappush_max Linked here; links to this page; shared tags: #heapq, #stdlib
- tuts/python3/stdlib_module/heapq/heappushpop_max Linked here; links to this page; shared tags: #heapq, #stdlib
- tuts/python3/stdlib_module/heapq Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/heapq/heapify Linked here; shared tags: #heapq, #stdlib
- tuts/python3/stdlib_module/heapq/heapify_max Linked here; shared tags: #heapq, #stdlib
- tuts/python3/stdlib_module/heapq/heappop Linked here; shared tags: #heapq, #stdlib
- tuts/python3/stdlib_module/heapq/heappop_max Linked here; shared tags: #heapq, #stdlib
- tuts/python3/stdlib_module/heapq/heappush shared tags: #heapq, #stdlib
- tuts/python3/stdlib_module/heapq/heapreplace shared tags: #heapq, #stdlib
- tuts/python3/stdlib_module/heapq/heapreplace_max shared tags: #heapq, #stdlib