# Heap (Data Structure)

> A tree that keeps the smallest item on top, or the largest.

**Field:** Software Development  
**Category:** Algorithms & Data Structures  
**Also known as:** Heap, Min-Heap, Max-Heap, Priority Queue

## Think of it like

Think of it like a doctor's waiting room. The sickest person goes next.

## Definition

A heap is a tree that always keeps the smallest item at the top, or the largest in a max-heap. It does not keep everything in order, only enough to find the top item at once. Taking the top item out and adding a new one each take about log n steps. That makes it the usual way to build a priority queue. Python's heapq module gives you one on a plain list.

## Example

Jack's task runner keeps jobs in a heap by urgency. Whatever is most urgent comes out next, even if it arrived last.

## Example code

```python
>>> import heapq
>>> h = [5, 1, 8]
>>> heapq.heapify(h)
>>> heapq.heappop(h)
1
```

The smallest number always comes out first.

## Why it matters

Heaps pick the next job in task lists. Map apps use them to find short routes too.

## Common mistake

Mixing up this heap with the heap in memory. They share a name and nothing else.

## Three principles

- **Top item first.** Smallest or largest.
- **Partly sorted.** Just enough for the top.
- **A priority queue.** Its most common use.

## Related terms

- [Binary Tree](https://learn.benibix.com/term/development/binary-tree)
- [Queue (Data Structure)](https://learn.benibix.com/term/development/queue)
- [Dijkstra's Algorithm](https://learn.benibix.com/term/development/dijkstras-algorithm)
- [Tree (Data Structure)](https://learn.benibix.com/term/development/tree)

## Told apart from

- [Heap vs Binary Search Tree (BST)](https://learn.benibix.com/compare/heap-vs-binary-search-tree): People think a heap keeps its items sorted, like a binary search tree. It does not. A search tree keeps every value in order, so you can find any one fast. A heap only keeps the smallest item on top. Pick a heap when you only need the next smallest, and a search tree to look up any value.

---

Source: https://learn.benibix.com/term/development/heap
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-19
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
