How to Heapify a List into a Min Heap with heapq in Python
Convert any list into a valid min heap in-place using Python's heapq.heapify(), then pop the smallest element to verify heap order.
Python code
11 linesimport heapq
data = [5, 3, 8, 1, 9, 2, 7, 4, 6]
print("Original list:", data)
heapq.heapify(data)
print("Min heap:", data)
popped = heapq.heappop(data)
print("Smallest element popped:", popped)
print("Heap after pop:", data)
Output
Original list: [5, 3, 8, 1, 9, 2, 7, 4, 6]
Min heap: [1, 3, 2, 4, 9, 8, 7, 5, 6]
Smallest element popped: 1
Heap after pop: [2, 3, 6, 4, 9, 8, 7, 5]
How it works
heapq.heapify(data) rearranges the list in-place so that it satisfies the heap property: every parent node is smaller than or equal to its children. The resulting heap is stored as a regular list, where the smallest element is always at index 0. heapq.heappop removes and returns the smallest element, then restores the heap property with an efficient O(log n) operation. This gives fast access to the minimum without fully sorting the list.
Common mistakes
- Forgetting that heapify works in-place and modifies the original list.
- Expecting the list to be fully sorted after heapify — it only guarantees the smallest element is first.
- Using `heapq.heappush` without first heapifying an existing list, leading to an invalid heap.
- Assuming `heappop` returns the smallest element after manual list modifications break the heap invariant.
Variations
- Use `heapq.nsmallest(k, data)` to get the k smallest elements without explicitly calling heapify.
- Build a heap incrementally with `heapq.heappush` for streaming data instead of heapifying an existing list.
Real-world use cases
- Implementing a priority queue for task scheduling where the highest-priority item is always processed next.
- Maintaining a running median of a stream of numbers by using two heaps (min and max).
- Efficiently merging multiple sorted lists by pushing their heads into a min heap.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.