Abstract flowing gradient in deep indigo and blue tones, smooth and luminous, evoking a modern digital learning atmosphere

Computer Science and programming articles. We do not sell courses.

Building a Min-Heap with Python Lists and Heapify

A min-heap is a complete binary tree in which every parent is less than or equal to its children. The smallest value therefore sits at the root, making the structure useful when an algorithm repeatedly needs the next-lowest item. Python lists provide a compact way to store this tree without creating separate node objects or pointer references.

This approach is valuable for priority queues, graph algorithms, scheduling systems and streaming data. For example, a Melbourne public transport application could use a heap to process upcoming departures, while a Brisbane alert system could prioritise weather events by urgency. The central technique is heapify: rearranging an ordinary list until it satisfies the min-heap property.

Why a min-heap is useful

A sorted list keeps every value in order, but inserting a new item can require shifting many elements. A min-heap does not maintain complete sorted order. It maintains just enough order to guarantee that the smallest item is available at index 0. This trade-off makes insertion and removal efficient.

For a heap containing n values, reading the minimum takes O(1) time. Inserting an item and removing the minimum both take O(log n) time because an element moves along the height of the tree. Building a heap from an existing list with bottom-up heapify takes O(n), which is faster than inserting all items individually.

Priority queues are common in Australian software systems. A Sydney delivery platform might select the next job by promised delivery time, while a supermarket stock service could prioritise products with the earliest expiry date. The heap stores the priorities efficiently, even when the underlying records contain names, timestamps and other fields.

Mapping the tree onto a list

The list representation uses zero-based indexing. For an element at index i, its parent is at:

parent = (i - 1) // 2

Its children are at:

left = 2 * i + 1
right = 2 * i + 2

An index is a leaf when it has no child index smaller than the list length. Since all levels of the tree are filled from left to right, the structure remains complete automatically. No explicit tree nodes are needed.

Consider this list:

values = [2, 5, 7, 9, 6, 11, 8]

It represents a tree with 2 at the root, 5 and 7 beneath it, and the remaining values on the next level. Every parent is smaller than its children, so this list already satisfies the min-heap rule. The list is not fully sorted, and that is expected.

Equal values are valid. The heap property allows a parent to be less than or equal to a child, so duplicate priorities do not require special handling. When priorities tie, a separate counter can be stored to preserve insertion order.

How bottom-up heapify works

Heapify repairs a list from the lowest internal node towards the root. Leaves are already valid heaps because they have no descendants. The last internal node is located at (n // 2) - 1, so the algorithm moves backwards from that index to 0.

At each position, the algorithm compares the current value with its smallest child. If the child is smaller, the two values are swapped and the process continues from the child’s new position. This operation is often called sift-down or percolate-down.

def sift_down(heap, index, size):
    while True:
        left = 2 * index + 1
        right = 2 * index + 2
        smallest = index

        if left < size and heap[left] < heap[smallest]:
            smallest = left

        if right < size and heap[right] < heap[smallest]:
            smallest = right

        if smallest == index:
            return

        heap[index], heap[smallest] = heap[smallest], heap[index]
        index = smallest


def heapify(heap):
    for index in range(len(heap) // 2 - 1, -1, -1):
        sift_down(heap, index, len(heap))

Although some nodes may move several levels, bottom-up heapify is O(n). Most nodes are near the bottom and can move only a short distance. Only a small number of nodes are high enough to travel through many levels.

Implementing insertion and removal

To insert a value, append it to the end of the list. The new item is initially a leaf, so the heap remains complete. It may violate the ordering rule with its parent, though. Sift-up repeatedly swaps it with its parent until the parent is smaller or the item reaches the root.

Removing the minimum follows a different pattern. Save the root, move the final list element to index 0, remove the final slot, and sift the replacement down. The smaller child must be selected at every step; swapping with an arbitrary child could leave a smaller descendant below the new parent.

def push(heap, value):
    heap.append(value)
    index = len(heap) - 1

    while index > 0:
        parent = (index - 1) // 2

        if heap[parent] <= heap[index]:
            break

        heap[parent], heap[index] = heap[index], heap[parent]
        index = parent


def pop_min(heap):
    if not heap:
        raise IndexError("pop from an empty heap")

    minimum = heap[0]
    last = heap.pop()

    if heap:
        heap[0] = last
        sift_down(heap, 0, len(heap))

    return minimum

The pop_min operation removes the smallest value, but it does not return the list in sorted order. Repeating it until the heap is empty produces values in ascending order, which is one way to implement heap sort. A dedicated priority queue can use the same operations while keeping the list private.

A reusable heap class

A class provides a clear interface and prevents callers from accidentally breaking the internal list. The constructor copies the supplied iterable before heapifying it, so the caller’s original list is unchanged. This is often safer when the input is shared with another part of a program.

class MinHeap:
    def __init__(self, values=None):
        self.data = list(values) if values is not None else []
        heapify(self.data)

    def __len__(self):
        return len(self.data)

    def peek(self):
        if not self.data:
            raise IndexError("peek from an empty heap")
        return self.data[0]

    def push(self, value):
        push(self.data, value)

    def pop(self):
        return pop_min(self.data)

A heap can store tuples when a value has several sorting fields. Python compares tuples lexicographically, so (priority, sequence_number, task) first uses priority and then the sequence number. This is useful when two jobs have the same priority and should be processed in arrival order.

Graph algorithms also depend on repeated minimum extraction. For a broader comparison of minimum-spanning-tree techniques, the reverse-delete walkthrough shows a contrasting strategy, while a heap-based priority queue is especially natural in algorithms such as Prim’s.

Complexity, correctness and testing

The heap invariant can be checked by inspecting every parent and its children. A simple validation function is useful during development:

def is_min_heap(heap):
    for index in range(len(heap) // 2):
        left = 2 * index + 1
        right = 2 * index + 2

        if left < len(heap) and heap[index] > heap[left]:
            return False

        if right < len(heap) and heap[index] > heap[right]:
            return False

    return True

Test an empty heap, a single-item heap, duplicate values, negative numbers and an already sorted list. Also test a reverse-sorted list because it causes many values to move during heapify. After each push and pop, is_min_heap should return True, and repeated removals should match Python’s sorted result.

The auxiliary space used by the in-place heapify operation is O(1) apart from the list itself. The class constructor above makes a copy, so constructing the object from an existing list uses O(n) additional space. This distinction matters for large datasets, such as market price events or sensor records collected across regional Australian offices.

For minimum-spanning trees, a priority queue can repeatedly select the cheapest available edge. The Kruskal algorithm tutorial uses a different primary strategy, sorting edges and tracking connected components, but understanding heaps helps when comparing the cost of alternative graph implementations.

Practical recommendations

Use a heap when the program repeatedly needs the smallest or highest-priority item, rather than when it needs fast searches for arbitrary values. Membership tests and deletion of a specific non-root element are not efficient in a basic list-backed heap. A dictionary or a different data structure may be better when those operations dominate.

For applications that process Australian customer information, timestamps or location data, keep privacy requirements in mind. The Privacy Act 1988 and the Australian Privacy Principles can affect how personal information is collected, stored and disclosed. A heap should hold only the fields required for prioritisation, such as an internal identifier and a due time, instead of copying unnecessary personal data.

A straightforward list-backed implementation is enough for many teaching projects, scripts and production components. When the data model becomes richer, the same invariant still applies: every parent must remain no greater than either child. For implementation discussions or corrections related to this tutorial, the contact page provides a direct way to reach hello ML.