---
source: https://iinventedlight.com/library/notes/python-heapq.md
title: "Python heapq keeps a list as a min-heap for priority queues and n-smallest queries"
license: CC-BY-4.0
license_url: https://creativecommons.org/licenses/by/4.0/
source_license: "PSF-2.0 (Python docs); PSF-2.0 (python/cpython (GitHub)); prose restates cited source lines in own words"
license_family: mixed-green
attribution: "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."
author: "iinventedlight (synthesis of cited sources); text drafted with AI assistance"
date: 2026-11-18
status: published
approved_by: "Cole Withington, 2026-11-20 13:14 PT: \"Publish the full batch and rewrite the 6 live notes\""
checked_on: 2026-11-18
as_of: 2026-11-18
confidence: medium
untested: "Not reproduced (2026-11-18). Official docs and source files were read; no test suite, server, or API call was run for this note."
category: coding-references
topic_area: "code-python: heapq"
tags: [python, heapq, heap, priority-queue, stdlib, algorithms]
client: Librarian
sources:
  - id: S1
    title: "heapq — Heap queue algorithm"
    publisher: Python docs
    url: https://docs.python.org/3/library/heapq.html
    accessed: 2026-11-18
    license: "PSF-2.0"
  - id: S2
    title: "Lib/heapq.py"
    publisher: python/cpython (GitHub)
    url: https://github.com/python/cpython/blob/main/Lib/heapq.py
    accessed: 2026-11-18
    license: "PSF-2.0"
---
# 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

```python
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

- `heappop` raises `IndexError` if the heap is empty; use `heap[0]` to see the smallest item without popping it.
- `heappushpop(heap, item)` pushes then pops, which runs more efficiently than separate calls; it returns the smaller of the two values.
- `nlargest(n, iterable, key=None)` is equivalent to `sorted(iterable, key=key, reverse=True)[:n]`, and `nsmallest` to `sorted(iterable, key=key)[:n]`.
- Python 3.14 added max-heap versions with a `_max` suffix, such as `heapify_max`, `heappush_max` and `heappop_max`.

## 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[2*k+1]` and `heap[k] <= heap[2*k+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

- [python-bisect](https://iinventedlight.com/library/notes/python-bisect/)
- [python-collections-containers](https://iinventedlight.com/library/notes/python-collections-containers/)
- [python-itertools](https://iinventedlight.com/library/notes/python-itertools/)

## Claims

- id: C1
  claim: The smallest element of a min-heap is always the root.
  source: S1
  evidence: "its smallest element is always the root"

- id: C2
  claim: heapify transforms a list into a min-heap in linear time.
  source: S1
  evidence: "Transform list x into a min-heap, in-place, in linear time."

- id: C3
  claim: The entry count serves as a tie-breaker.
  source: S1
  evidence: "The entry count serves as a tie-breaker"

- id: C4
  claim: heappop pops the smallest item from the heap.
  source: S2
  evidence: "# pops the smallest item from the heap"

## Sources

- [S1] heapq — Heap queue algorithm. Python docs. https://docs.python.org/3/library/heapq.html . License: PSF-2.0. Accessed 2026-11-18.

- [S2] Lib/heapq.py. python/cpython (GitHub). https://github.com/python/cpython/blob/main/Lib/heapq.py . License: PSF-2.0. Accessed 2026-11-18.

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.

---

Agents: [/agents.md](/agents.md) | [/.well-known/agent-library.json](/.well-known/agent-library.json).
