The heapq
module maintains the heap invariant, which is not the same thing as maintaining the actual list object in sorted order.
Quoting from the heapq
documentation:
Heaps are binary trees for which every parent node has a value less than or equal to any of its children. This implementation uses arrays for which
heap[k] <= heap[2*k+1]
andheap[k] <= heap[2*k+2]
for allk
, counting elements from zero. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that its smallest element is always the root,heap[0]
.
This means that it is very efficient to find the smallest element (just take heap[0]
), which is great for a priority queue. After that, the next 2 values will be larger (or equal) than the 1st, and the next 4 after that are going to be larger than their 'parent' node, then the next 8 are larger, etc.
You can read more about the theory behind the datastructure in the Theory section of the documentation. You can also watch this lecture from the MIT OpenCourseWare Introduction to Algorithms course, which explains the algorithm in general terms.
A heap can be turned back into a sorted list very efficiently:
def heapsort(heap):
return [heapq.heappop(heap) for _ in range(len(heap))]
by just popping the next element from the heap. Using sorted(heap)
should be faster still, however, as the TimSort algorithm used by Python’s sort will take advantage of the partial ordering already present in a heap.
You'd use a heap if you are only interested in the smallest value, or the first n
smallest values, especially if you are interested in those values on an ongoing basis; adding new items and removing the smallest is very efficient indeed, more so than resorting the list each time you added a value.