designwithfocus

Programming basics

What Is a Heap Data Structure? Parents, Children, Priority

By Design With Focus Team 6 min read
A simple complete binary tree with the smallest value drawn at the root

Short answer

A heap is a complete binary tree where each parent is ordered against its children. Python heapq is a min-heap: every parent is less than or equal to its children, and the smallest item is at index 0. heappush and heappop keep that order. heapify builds the heap in linear time.

Last verified against the sources listed below.

Key takeaways

  • Wikipedia: a binary heap is a complete binary tree, last level filled from the left.
  • A min-heap parent is less than or equal to its children. A max-heap parent is greater.
  • Python's heapq uses zero-based lists: children of k are at 2*k+1 and 2*k+2.
  • heappush adds an item. heappop removes the smallest. An empty pop raises IndexError.
  • The docs say heapify is linear time, and a heapsort built from push and pop is O(n log n).

What is a heap data structure? It is a complete binary tree in which each parent stays ordered against its children, so the extreme value sits at the root.

Programming uses a heap when the next item should be the smallest or the largest, not the one you inserted last.

Python ships that idea in heapq. The structure is still a list. The order rule is what makes the list a heap.

What shape is a heap?

A binary heap is a complete binary tree, and a min-heap keeps the parent less than or equal to its children.

Wikipedia states the shape property: every level is full except possibly the last, and the last level is filled from the left. It then splits the order. A max-heap parent is greater than or equal to its children.

A min-heap parent is less than or equal to its children.

Python’s heapq documentation uses the min-heap rule, and it stores the tree in a list with zero-based indexes. For each index k that has children, heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2]. The smallest item is heap[0].

Wikipedia gives those same child indexes when the root is at index 0, and the parent of index i is floor((i - 1) / 2).

The library reference’s list type is the container under that formula. A list is a mutable sequence. heapq does not replace it with a dictionary.

An associative array, as Wikipedia defines it, stores each key once and looks the value up by that key. A heap answers a different question: what is the current extreme?

Which functions move items?

heappush inserts. heappop removes the smallest. heapify builds the order in place.

Operation heapq function What the docs say
Build a min-heap in place heapify(list) Linear time
Add an item heappush(heap, item) Keeps the min-heap invariant
Remove the smallest heappop(heap) IndexError if the heap is empty
Push, then pop the smallest heappushpop(heap, item) Faster than the two calls separately
Pop, then push heapreplace(heap, item) Size stays the same. IndexError if empty
Build a max-heap heapify_max(list) Added in Python 3.14

The page’s heapsort pushes every value, then pops them into a new list. The result for [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] is the numbers from 0 through 9. The docs say this sort is not stable.

sorted is the stable alternative when equal items must keep their original order.

Max-heap names end in _max and were added in 3.14. The documentation header on the page I used is the Python 3.15.2 library reference. Until you are on 3.14 or newer, the supported API is the min-heap.

Tuples are allowed. The docs push (priority, task) pairs, and heappop returns the pair with the smallest priority first, because tuple order compares the priority before the task. If two tasks are not ordered and the priorities match, that comparison can fail.

The page’s fix is a third element, a rising count, so the tasks themselves are never compared.

Why is the root special?

The root is the current winner of the order rule, so removing it tells you the next priority.

The theory section compares the layout to a tournament. Index 0 is the overall winner as long as the invariant holds. To remove it, you move some other item into position 0 and percolate it down until the parent-and-children rule is true again.

The page calls that step logarithmic in the number of items. Doing it for every item produces an O(n log n) sort.

Wikipedia describes the same insert and remove idea, and it states both as O(log n). heapify is the exception the Python docs call out as linear time, because it builds the heap from the bottom instead of pushing one item at a time.

A word counter can measure a note you write next to a sketch of the tree. The sketch still needs the indexes. Label the root 0, its children 1 and 2, and the next pair 3 and 4.

Those are 2*k+1 and 2*k+2 for k equal to 0 and then 1.

What mistakes break the invariant?

The usual miss is treating the list as sorted, or mixing a 1-based textbook diagram with Python’s 0-based list.

  1. Reading heap[1] as the minimum. In heapq, the minimum is heap[0].
  2. Appending with list.append and skipping heappush. The new item sits at the end and can break the parent rule.
  3. Copying a diagram whose root is index 1. Those children live at 2i and 2i+1, which is not the Python formula.
  4. Comparing tasks that have no order, inside a (priority, task) tuple, when two priorities match.
  5. Expecting a stable sort from the push-then-pop example. The docs say it is not stable.

Keep the heap for “next smallest” or, on 3.14 and newer, “next largest.” If you need the item named ada, you wanted a dictionary. If you need the third item in insertion order, you wanted a plain list. The heap is the list plus the parent rule, not a substitute for either question.

How is a heap different from a map?

A heap returns an extreme element. A map returns the value stored under a key.

MDN’s Map keeps key-value pairs in insertion order, and each key occurs once. That is a dictionary. heapq will not answer scores[“ada”].

It will answer heap[0], the current minimum, after heappush has restored the parent rule.

C++ std::priority_queue is the same idea in another standard library. Cppreference says it is an adaptor over a random-access container, vector by default, with constant-time lookup of the largest element and logarithmic insertion and extraction. Passing std::greater makes the smallest element the top, which is the min-heap direction Python uses by default.

You still do not get lookup by name. If the next step in the program is “the item called ada,” leave the heap and use a dictionary.

Frequently asked questions

What is a heap data structure in plain terms?

It is a complete binary tree with an order rule between each parent and its children. Wikipedia calls the complete shape the shape property: every level is full except possibly the last, and the last level is packed from the left. A min-heap says the parent is less than or equal to the children. A max-heap says the parent is greater than or equal to the children.

Is Python's heapq a min-heap or a max-heap?

The heapq page says the unqualified word heap means a min-heap. The smallest item is heap[0]. heappush keeps the min-heap invariant, and heappop returns the smallest item. Max-heap helpers, heapify_max, heappush_max, and heappop_max, were added in Python 3.14. The page you are reading in the 3.15.2 library docs still treats the older names as the min-heap API. Comparisons use only the less-than operator, for both kinds of heap.

How do parent and child indexes work?

Python's docs store the heap in a list counted from zero. For every index k that has children, heap[k] is less than or equal to heap[2*k+1] and heap[2*k+2]. Wikipedia gives the same child indexes when the root is at index 0, and it puts the parent of i at floor((i-1)/2). If a textbook starts the array at 1, the children are at 2i and 2i+1 instead.

What do heappush and heappop do on an empty heap?

heappush on a list you started as [] turns that list into a one-item heap. heappop on an empty heap raises IndexError. heapreplace also raises IndexError on an empty heap, because it pops before it pushes. heappushpop pushes first, so it can run on an empty heap and then return the smallest item, which may be the item you just pushed. To read the minimum without removing it, use heap[0] after the heap is non-empty.

Does the documentation state a speed?

Yes, in a few places, and this guide does not add others. heapify and heapify_max transform a list in place in linear time. The theory section says removing the root and percolating a replacement down the tree is logarithmic in the number of items, and that repeating that over every item yields an O(n log n) sort. The heapsort example on the page is not stable, unlike sorted. Wikipedia separately says insert and remove are O(log n). Those are the figures the two pages state.

Sources