You're reading millions of scored items, such as search results or log events, and need the k largest. Sorting everything is and needs all the data in memory. A size-k min-heap does it in in one pass.
Implement top_k(stream, k, key=lambda x: x):
stream is any iterable (possibly a generator you can only read once).key, sorted from largest to smallest. If several items tie, the one that appeared earlier comes first.[] for k <= 0.Don't sort the whole stream or call heapq.nlargest. Write the heap logic yourself with heapq.heappush and heapq.heappushpop.