Heap Functions

heapq.heappushpop()

Push then pop the smallest of the combined items efficiently. If the new item is smaller than the root, the existing heap remains unchanged.

Formal Syntax & Structure

python syntaxpython
heapq.heappushpop(heap, item, /)

Parameters & Attributes

NameTypeDescription
heaplistMutable list satisfying the min-heap invariant unless heapifying.
itemobjectComparable item to add.

Return Value

object

The object result described above.

Working Example

Example Snippetpython
import heapqheap=[2,3]print((heapq.heappushpop(heap,4),sorted(heap)))
Python Reference