Python Glossary Русский

all Python 3heapqterm

Heap as a priority queue

usage

The classic pattern: keep (priority, data) tuples in a heap to schedule tasks efficiently.

Syntax

heapq.heappush(pq, (priority, task))
priority, task = heapq.heappop(pq)

Tuples compare element by element, so when two priorities tie Python moves on to the payload — with dicts or custom objects that means TypeError. The fix is a third field, a monotonically increasing counter, as in (priority, count, task), which also gives FIFO order among equal priorities. And heapq is a min-heap: if a bigger number means more important, push -priority.

Examples

import heapq
pq = []
heapq.heappush(pq, (2, 'wash dishes'))
heapq.heappush(pq, (1, 'urgent call'))
heapq.heappush(pq, (3, 'read book'))
prio, task = heapq.heappop(pq)
print(task) # → urgent call
prio, task = heapq.heappop(pq)
print(task) # → wash dishes

See also

Open in the full glossarydocs.python.orgReport an inaccuracy