all Python 3heapqterm
heapq
module
A binary heap on top of a plain list: get the smallest item fast, a priority queue, the k largest items.
Syntax
import heapq
heapq is for repeatedly taking the minimum from a changing collection: a task queue, Dijkstra's algorithm, merging sorted streams. A heap is a plain list whose order the module's functions maintain; the list itself is not sorted, only nums[0] is guaranteed smallest. Between threads use queue.PriorityQueue. The heap here is a min-heap: a max-heap used to be made by negating the numbers.
Examples
import heapq
nums = [5, 1, 8, 3]
heapq.heapify(nums)
heapq.heappush(nums, 0)
print(heapq.heappop(nums), heapq.heappop(nums)) # → 0 1
print(heapq.nlargest(2, [5, 1, 8, 3])) # → [8, 5]
See also
Open in the full glossarydocs.python.orgReport an inaccuracy