heapq.heapify() method converts a list into a valid min-heap. After heapification, the smallest element is placed at the beginning of the list, allowing efficient retrieval of the minimum value using heap operations.
Example: The following example converts a normal list into a min-heap.
import heapq
nums = [5, 2, 8, 1, 9]
heapq.heapify(nums)
print(nums)
Output
[1, 2, 8, 5, 9]
Explanation: heapq.heapify(nums) rearranges the elements of nums to satisfy the min-heap property, where the smallest element is always stored at index 0.
Syntax
heapq.heapify(x)
- Parameters: x - A list that will be converted into a min-heap.
- Return Value: Returns None. The original list is modified in place.
Examples
Example 1: The following example converts a list of numbers into a min-heap. The smallest value becomes the first element of the list.
import heapq
nums = [8, 4, 7, 1, 3]
heapq.heapify(nums)
print(nums)
Output
[1, 3, 7, 4, 8]
Explanation: heapq.heapify(nums) rearranges the list to maintain the min-heap property. The smallest element (1) is placed at index 0.
Example 2: The following example uses heapify() before removing the smallest element from the heap using heappop().
import heapq
nums = [12, 5, 9, 2, 18]
heapq.heapify(nums)
smallest = heapq.heappop(nums)
print(smallest)
print(nums)
Output
2 [5, 12, 9, 18]
Explanation: After heapq.heapify(nums), heapq.heappop(nums) removes and returns the smallest element (2) from the heap.
Example 3: The following example creates a priority queue using tuples, where smaller priority values are processed first.
import heapq
tasks = [(3, "Write Report"),
(1, "Check Email"),
(2, "Attend Meeting")]
heapq.heapify(tasks)
print(heapq.heappop(tasks))
Output
(1, 'Check Email')
Explanation: heapq.heapify(tasks) organizes the tuples based on the first value of each tuple. heapq.heappop(tasks) returns the tuple with the smallest priority value (1).
Applications
- Priority Queues: Organizing tasks based on priority so higher-priority tasks can be processed first.
- Graph Algorithms: Used in algorithms such as Dijkstra's Shortest Path Algorithm and A* Search Algorithm, where the next minimum-cost node must be selected efficiently.
- Heap Sort: Preparing data for heap-based sorting operations.
- Merging Sorted Data: Efficiently combining and processing multiple sorted sequences using heap operations.
- Real-Time Scheduling: Managing jobs, events or requests that need to be processed in a specific order.