I don't understand how I can properly use heapq module.
I realized that without transforming my list to a heap (without using heapify) I can still use other functions which require a heap as input (heappop, heappush..). So when do I need to use heapify?
Should I create an empty list, transform it to a heap using heapify, and then use it? I tried this. I got TypeError.
my_list = heapq.heapify([0])
heapq.heappush(my_list, -8)
TypeError: heap argument must be a list
heapq.heappush(my_list, -8)
In the example below I can push -8 to my list with heappush if I don't transform my list to a heap. However when I want to see the min element of the heap, it gives me 0. In the heapq documentation it says that I can reach the min element using the index 0.
my_list = [0]
heapq.heappush(my_list, -8)
print(my_list, my_list[0])
output: [0, -8] 0
I'm trying to use it in a loop, so I want to be able to perform quick push and pop operations without transforming a list to a heap in each iteration, it would take O(N)