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)- Expected output: 1 urgent 2 report 3 cleanup
- 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