heapq

Python's standard-library module of functions that treat an ordinary list as a binary min-heap.

In more detail

heappush and heappop add and remove the smallest item in O(log n); heapify builds a heap in O(n); nlargest and nsmallest return the top k items efficiently; merge merges sorted inputs. Entries are often tuples such as (priority, task), which compare by priority first.

Example

heapq.heappush(h, (2, "write report")); heapq.heappop(h)

Related terms

Taught in

References