Python heapq.heapify() Method (original) (raw)

Last Updated : 23 Jul, 2025

The heapq.heapify() function in Python is used to transform a regular list into a valid min-heap. A min-heap is a binary tree where the smallest element is always at the root. This method is highly useful when you need to create a heap structure from an unordered list and maintain the heap property efficiently.

**Example: Converting a List into a Min-Heap

Python `

import heapq

Create a regular list

a = [3, 1, 5, 7, 9, 2]

Convert the list into a heap

heapq.heapify(a)

print("Min-Heap:", a)

`

Output

Min-Heap: [1, 3, 2, 7, 9, 5]

**Explanation:

Syntax of heapify() method

heapq.heapify(iterable)

Parameters

Return Value

The heapq.heapify() method does not return anything. It modifies the input list in place, ensuring that the list satisfies the heap property, where the smallest element is at the root.

How Does heapq.heapify() Work?

Examples of heapify() method

**1. **Using heapq.heapify() on a Custom List

Python `

import heapq

Create a custom list

a = [8, 4, 3, 9, 2, 5]

Convert the list into a heap

heapq.heapify(a)

print("Heapified List:", a)

`

Output

Heapified List: [2, 4, 3, 9, 8, 5]

**Explanation:

**2. Using heapq.heapify() to Implement a Priority Queue

Python `

import heapq

List of tasks with (priority, task)

a = [(2, "Task A"), (1, "Task B"), (3, "Task C")]

Convert the list into a heap

heapq.heapify(a)

Pop the task with the highest priority (lowest priority value)

priority, a = heapq.heappop(a)

print("Highest priority task:", a)

`

Output

Highest priority task: Task B

**Explanation:

When to Use heapq.heapify()?

You can use heapq.heapify() when you need to efficiently create a heap from an unordered list. Some common use cases include: