Codectionary / Developer documentation / Python

Priority Queues with heapq

heapq maintains a min-heap in a list, allowing efficient extraction of the smallest entry. A heap is not a fully sorted list. Run as a Python 3.11+ script.

Syntax

heapq.heapify(items); heapq.heappush(items, value); heapq.heappop(items)

Examples

Priority Queues with heapq

Run as a Python 3.11+ script.

import heapq
jobs = [(3, "cleanup"), (1, "urgent")]
heapq.heapify(jobs)
heapq.heappush(jobs, (2, "report"))
while jobs:
    priority, name = heapq.heappop(jobs)
    print(priority, name)
  1. Expected output: 1 urgent 2 report 3 cleanup
  2. Tuple comparison orders by priority first, then the name on a tie. Repeated pops yield ascending priorities.

Best practices

  • Add a monotonically increasing tie-breaker when payloads cannot be compared.
  • Do not mutate queued priorities in place; restore the heap invariant after changes.

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading