Python Heap Data Structure Implementation using heapq module

Python Heap Data Structure Implementation using heapq module

Instructor-svgAl-Mamun Sarkar
Mar 28 , 2020

Python Heap Data Structure Implementation using heapq module. The following code shows how to implement a min-heap using heapq module in the Python programming language. 

Code:

import heapq

min_heap = [21, 1, 45, 78, 3, 5]
heapq.heapify(min_heap)
print(min_heap)

# Insert into min_heap
heapq.heappush(min_heap, 8)
print(min_heap)

# Remove element form min_heap
heapq.heappop(min_heap)
heapq.heappop(min_heap)
heapq.heappop(min_heap)
heapq.heappop(min_heap)
print(min_heap)
heapq.heapreplace(min_heap, 150)
print(min_heap)

 

Output:

[1, 3, 5, 78, 21, 45]
[1, 3, 5, 78, 21, 45, 8]
[21, 78, 45]
[45, 78, 150]

 

  • Share On:
  • fb
  • twitter
  • pinterest
  • instagram