Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I print a heap queue?

Tags:

python

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?

like image 275
george mano Avatar asked Dec 07 '25 04:12

george mano


1 Answers

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.

like image 187
unwind Avatar answered Dec 08 '25 16:12

unwind