jpaulus jpaulus - 1 year ago 86
Python Question

Python: heapq.heappop() gives strange result

I'm trying to use the Python module

in my program but I ran into a strange problem using
. The function does not appear to return the smallest element in the heap. Take a look at the following code:

Python 2.7.12 (default, Jul 1 2016, 15:12:24)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import heapq
>>> list = [[1326, 'a'], [654, 'b']]
>>> print heapq.heappop(list)
[1326, 'a']
>>> print heapq.heappop(list)
[654, 'b']

not return
[654, 'b']
first and then
[1326, 'a']

Answer Source

You should "heapify" the list first (an in-place operation):

In [1]: import heapq

In [2]: l = [[1326, 'a'], [654, 'b']]

In [3]: heapq.heapify(l)

In [4]: heapq.heappop(l)
Out[4]: [654, 'b']

In [5]: heapq.heappop(l)
Out[5]: [1326, 'a']

And, avoid naming your list as list - you are shadowing the built-in list keyword.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download