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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 14 views 0 copies

Python code

11 lines
Python 3.9+
import 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

stdout
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

  1. Use `heapq.nsmallest(k, data)` to get the k smallest elements without explicitly calling heapify.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.