Python Glossary Русский

Python 3.14+heapqfunction

heapq.heappush_max()

operations

Pushes an item onto a max-heap so that the largest item stays at heap[0]. It is the max-heap counterpart of heappush().

Syntax

heapq.heappush_max(heap, item) -> None

Added in Python 3.14; before that a max-heap was faked by pushing negated numbers (-x) into a regular heap and flipping the sign back on pop, a trick that does not work for strings or objects at all. Using list.append() instead silently breaks the heap: the item stays at the end and never sifts up. Items must be comparable: (priority, obj) tuples with equal priorities compare the objects and may raise TypeError, so add a counter as the second field.

Examples

import heapq
h = []
for x in [5, 1, 8, 3]:
    heapq.heappush_max(h, x)
print(h[0])  # → 8
import heapq
h = [('low', 1), ('high', 3)]
heapq.heapify_max(h)
print(h[0])  # → ('low', 1) — строки сравниваются по алфавиту, а не по смыслу

See also

Open in the full glossarydocs.python.orgReport an inaccuracy