heapqEasy Examples

Heap queue algorithm (priority queue) on plain lists

Getting started with heapq

Basic import and usage of the heapq module.

python
import heapq

# Min-heap operations
nums = [5, 1, 8, 3, 9, 2, 7]
heapq.heapify(nums)
print(f"Heap: {nums}")
print(f"Smallest: {heapq.heappop(nums)}")
print(f"3 largest: {heapq.nlargest(3, [5, 1, 8, 3, 9])}")

The heapq module is part of Python's standard library. Heap queue algorithm (priority queue) on plain lists.

Common heapq operations

Frequently used functions from the heapq module.

python
# More heapq examples
import heapq

print(f"heapq module loaded successfully")
print(f"Location: {heapq.__name__}")
print(f"Has {len(dir(heapq))} attributes")

These are the most commonly used features of the heapq module.

Want to try these examples interactively?

Open Easy Playground