Heapq
Python’s heapq module implements a min-heap using a regular list. The smallest element is always stored at index 0.
My usecase was to have a performant collection with a maximum size that removes the worst results to focus on the best.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import heapq class element: score: int def __lt__(self, other): if not isinstance(other, element): return NotImplemented return self.score < other.score def do_something(): list: list[element] = [] ... heapq.heappush(list, new_element) heapq.heappushpop(list, new_element) |
- 17:
heappush(heap, item)inserts a new item while preserving the heap property. - 19:
heappushpop(heap, item)first inserts the item and then removes and returns the smallest element. It is usually more efficient than calling heappush() followed by heappop() separately.
Heap elements must be mutually comparable. For custom classes, implementing lt() is normally sufficient, because heapq compares elements using the < operator. If two elements cannot be compared, Python raises a TypeError. A common alternative is to store tuples such as (priority, value), where the first element defines the priority.
