Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

heapq.heappushpop

Combines insertion and removal, returning the smallest of the incoming item and the heap.

Version: Python 3.14; repository image, production runtime not attested

Syntax

heapq.heappushpop(heap, item, /)

Combines insertion and removal, returning the smallest of the incoming item and the heap.

An incoming item smaller than the root is returned immediately, leaving the existing heap unchanged.

For a fixed-size heap of candidates, keep the larger items and return the smallest of the incoming item and existing root. An empty heap returns the input and stays empty. With [4, 8], the incoming 2 goes straight back; 6 replaces the original root and the call returns 4.

from heapq import heappushpop
h = []
assert heappushpop(h, 3) == 3 and h == []
h[:] = [3, 7]
assert heappushpop(h, 2) == 2 and h == [3, 7]
assert heappushpop(h, 5) == 3 and sorted(h) == [5, 7]

Examples

import heapq
heap = [4, 8]
print(heapq.heappushpop(heap, 2), heap)
print(heapq.heappushpop(heap, 6), sorted(heap))

Result

2 [4, 8]
4 [6, 8]

For a fixed-size heap of candidates, keep the larger items and return the smallest of the incoming item and existing root. An empty heap returns the input and stays empty. With [4, 8], the incoming 2 goes straight back; 6 replaces the original root and the call returns 4.

Sources