What Is a Heap Data Structure Python?


Larry Thompson

A heap data structure is a specialized tree-based data structure that satisfies the heap property. In Python, a heap can be implemented using the built-in `heapq` module.

What is the Heap Property?

The heap property defines the relationship between parent and child nodes in a heap. There are two types of heaps: min-heap and max-heap.

In a min-heap, for any given node, its value is less than or equal to the values of its children. Conversely, in a max-heap, the value of any given node is greater than or equal to the values of its children.

Heap Operations

The `heapq` module in Python provides several functions to manipulate heaps:

  • heapify(iterable): This function converts an iterable into a valid heap structure.
  • heappush(heap, item): This function adds an element to the heap while maintaining the heap property.
  • heappop(heap): This function removes and returns the smallest element from the heap.
  • heappushpop(heap, item): This function combines both push and pop operations in one step. It pushes the item onto the heap and then pops out and returns the smallest element.
  • heapreplace(heap, item): This function replaces the smallest element with a new item while maintaining the heap property.

Creating a Heap

To create a min-heap in Python using `heapq`, you need to pass an iterable to the `heapify()` function. Here’s an example:

import heapq

numbers = [4, 2, 7, 1, 9]

[1, 2, 7, 4, 9]

Adding Elements to a Heap

To add elements to a heap, you can use the `heappush()` function. Let’s add a new element to our existing heap:

numbers = [1, 2, 7, 4, 9]
heapq.heappush(numbers, 3)

[1, 2, 3, 4, 9, 7]

Removing Elements from a Heap

To remove the smallest element from a heap (min-heap), you can use the `heappop()` function. Let’s remove the smallest element from our heap:

numbers = [1, 2, 3, 4 ,9 ,7]
smallest = heapq.heappop(numbers)

[2 ,4 ,3 ,7 ,9]


A heap data structure is an efficient way of managing elements based on their priority. With the help of Python’s built-in `heapq` module and its functions like `heapify()`, `heappush()`, and `heappop()`, you can easily create and manipulate heaps in your code.

Remember to import the `heapq` module before using any of its functions.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy