I have a list named mylist. If I enter print mylist in my program and I am able to print my list and see the items. I then transfer the list items into a heap queue:
myheap=heapq.heapify(mylist)
print myheap
It prints None. What is wrong?
You failed to read the docs:
heapify(x)Transform list x into a heap, in-place, in linear time.
The heapify() method convers the list in-place, it doesn't return a new list. You should print mylist:
>>> a=[43,12,4,1,5,3,5,3,5,2,64,352,36]
>>> import heapq
>>> heapq.heapify(a)
>>> a
[1, 2, 3, 3, 5, 4, 5, 12, 5, 43, 64, 352, 36]
As pointed out in a comment, this is a bit odd for a Pythonn API. I don't know for certain, but I guess it has been done for efficiency's sake. Still, of course the heapify() function could just return the input reference, to make it less surprising.
If the API had been a constructor, which returns a newly constructed object like you expected, it would very probably have been named differently, perhaps:
myheap = heapq.HeapQ(a) # This is not valid code.
The casing and naming of the function are both strong hints this is not a regular constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With