Python · Priority queue · functions

heapq

Functions that keep a plain list in min-heap order: O(log n) push and pop, O(1) peek at heap[0].

import heapq
module heapq (functions on a list)

CPython 3.14

Operations

OperationTimeWorst caseChanges the collection
heappushO(log n) (the list append is amortized O(1))O(log n)Yes
heappopO(log n)O(log n)Yes
heapifyO(n)O(n)Yes
heap[0]O(1)O(1)No

"Time" shows the amortized, expected or average bound when one applies; open an operation for the full profile and its assumptions.

How it works

Representation
A binary min-heap stored in the list you pass: heap[k] ≤ heap[2k + 1] and heap[k] ≤ heap[2k + 2].
Ordering
Only heap[0] is guaranteed to be the minimum; the rest of the list is heap-ordered, not sorted.
Duplicates
Allowed.
Mutability
The list is ordinary and mutable; editing it directly can break the heap invariant (call heapify again).
Memory and ownership
No extra structure: the heap is your list.
Equality and comparison
Elements are compared with <. Tuples (priority, counter, item) give a priority with stable FIFO tie-breaking and avoid comparing items.

C#, Java and C++ provide priority-queue classes or adapters; Python provides functions over a list.

Pitfalls

  • heapq is not a class; nothing stops you from calling list methods that break the heap order.
  • It is a min-heap only (heapq.heappush_max and friends were added in Python 3.14; on older versions negate numeric keys).
  • Equal priorities fall back to comparing the next tuple field, which fails if the items are not comparable: add a counter.

Alternatives

  • queue.PriorityQueue for threads (a locked wrapper around heapq)
  • sorted list + bisect when you also need ordered iteration

In other languages

References