Python: heapq.heappop() gives strange result
<p>I'm trying to use the Python module <code>heapq</code> in my program but I ran into a strange problem using <code>heapq.heappop()</code>. The function does not appear to return the smallest element in the heap. Take a look at the following code:</p>

<pre><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.
&gt;&gt;&gt; import heapq
&gt;&gt;&gt; list = [[1326, 'a'], [654, 'b']]
&gt;&gt;&gt; print heapq.heappop(list)
[1326, 'a']
&gt;&gt;&gt; print heapq.heappop(list)
[654, 'b']
</code></pre>

<p>Should <code>heappop()</code> not return <code>[654, 'b']</code> first and then <code>[1326, 'a']</code>?</p>

<p>You should <a href="https://docs.python.org/2/library/heapq.html#heapq.heapify" rel="nofollow">"heapify"</a> the list first (an in-place operation):</p>

<pre><code>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']
</code></pre>

<p>And, avoid naming your list as <code>list</code> - you are <em>shadowing</em> the built-in <code>list</code> keyword.</p>

python heap result pop