← All notes

Python heapq keeps a list as a min-heap for priority queues and n-smallest queries

Answer: Start from [] or call heapify(x), then use heappush(heap, item) and heappop(heap); the smallest element is always the root, heap[0]. For a priority queue, push (priority, count, task) entries so the entry count acts as a tie-breaker.

Example

import heapq, itertools

heap = []
counter = itertools.count()
heapq.heappush(heap, (2, next(counter), "write docs"))
heapq.heappush(heap, (1, next(counter), "fix bug"))
priority, _, task = heapq.heappop(heap)    # (1, ..., "fix bug")

nums = [5, 1, 8, 3]
heapq.heapify(nums)                         # in place, linear time
heapq.nlargest(2, [5, 1, 8, 3])             # [8, 5]
list(heapq.merge([1, 4], [2, 3]))           # [1, 2, 3, 4]

Functions

How it works

Min-heaps are binary trees where every parent node has a value less than or equal to any of its children. heapq uses zero-based lists with heap[k] <= heap[2k+1] and heap[k] <= heap[2k+2], so heap.sort() maintains the heap invariant.

Why the entry count

With plain (priority, task) pairs, tuple comparison breaks when priorities are equal and the tasks do not have a default comparison order.

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python docs, heapq — Heap queue algorithm; python/cpython (GitHub), Lib/heapq.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python docs, heapq — Heap queue algorithm; python/cpython (GitHub), Lib/heapq.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation.

Cite this

Permanent ID: iil:note:zwsx3mfn

iinventedlight. 2026. "Python heapq keeps a list as a min-heap for priority queues and n-smallest queries." iinventedlight Library, iil:note:zwsx3mfn, version of 2026-11-18. https://iinventedlight.com/library/notes/python-heapq/. License: CC-BY-4.0.

@misc{iil_note_zwsx3mfn,
  author = {{iinventedlight}},
  title = {{Python heapq keeps a list as a min-heap for priority queues and n-smallest queries}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-18},
  url = {https://iinventedlight.com/library/notes/python-heapq/},
  note = {Permanent ID iil:note:zwsx3mfn. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

Extra files beside this note

These files use this note's license, shown below. Paper extras retain their reproduction status; a link is not a reproduction.

All artifact files (JSON index)

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-heapq.md.