Skip to main content

Heap Implementation for Python

Project description

It’s like heapq (blazingly fast) but object-oriented + more features.


Less code.

What are heaps good for anyway?

When you need the smallest item of big collections—fast and with no overhead.


Suppose you have a heap, then use pop get the smallest item.

heap = Heap(['H', 'D', 'B', 'A', 'E', 'C', 'L', 'J', 'I'])
heap.pop()   # returns A
heap.pop()   # returns B
heap.pop()   # returns C
heap.pop()   # returns D

Heapsort works this way.

Can I insert an item?

Indeed and it’s as fast as pop. Use push for insertion.

heap = Heap(['A', 'D', 'B', 'H', 'E', 'C', 'L', 'J', 'I'])

Can I remove an item from the middle of a heap?

Yes, that’s what RemovalHeap.remove is supposed to do.

heap = RemovalHeap(['A', 'D', 'B', 'H', 'E', 'C', 'L', 'J', 'I'])

Can I specify the order of the heap?

Just imagine two heaps of the very same set of items but you need different sorting for each heap. That is what OrderHeap is designed for:

items = [date(2016, 1, 1), date(2016, 1, 2),  date(2016, 1, 3),  date(2016, 1, 4)]

day_heap = OrderHeap(items, key=lambda date:
day_heap.peek()      # returns date(2016, 1, 1)

weekday_heap = OrderHeap(items, key=lambda date: date.weekday())
weekday_heap.peek()  # returns date(2016, 1, 4)

What about both remove+order?

No problem. Use XHeap.

If you wonder why there are 4 distinct heap implementations, it’s a matter of speed. Each additional feature slows a heap down. Thus, you could always use XHeap but beware of the slowdown.

Checking Heap Invariant

A heap is just a list. So, if you tinker with it, you can check whether its invariant still holds:

heap = Heap([4, 3, 7, 6, 1, 2, 9, 8, 5])
heap[3] = 10           # I know what I am doing here
heap.check_invariant() # but better check... ooops



  • uses C implementation if available (i.e. fast)

  • object-oriented

  • no slowdown if you don’t need more than a simple heap

  • removal available

  • custom orders available

  • works with Python2 and Python3


  • no drawbacks discovered so far ;)

  • needs fix:

    • decrease-key and increase-key seem to be another important missing use-case of heapq; so, I will dig into that as well

    • merge heaps

  • ideas are welcome :-)

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

xheap-0.9.tar.gz (4.7 kB view hashes)

Uploaded source

Built Distribution

xheap-0.9-py2.py3-none-any.whl (3.9 kB view hashes)

Uploaded py2 py3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page