Python heapq.nlargest vs sorted: Top K, Ties and Streams
Choose nlargest, sorted, or max for Python top K. Test cutoff ties, one-shot iterators, and a bounded min-heap with runnable examples.
Use heapq.nlargest for a small set of ranked winners from a finite iterable, sorted when you need the full order, and max for one winner. Define what happens at the cutoff: keep input order, apply a secondary key, or include all equal scores and return more than K.
Choose what “top K” means before choosing a function
An alert report needs its three highest-scoring events. With scores 95, 95, 92, 92 and 92, there are several plausible reports. You might keep exactly three events and break the tie by arrival order, select a repeatable winner using a durable ID, or include every event at the cutoff. Those are different output contracts. A faster selection method cannot settle the policy for you.
For a finite iterable and a small positive K, heapq.nlargest is a clear default when you need a ranked list of winners. Use sorted when you need the full order, expect to keep most of the input, or want a simple reference for correctness. For one winner, max directly expresses the task. This guide uses integer scores and dictionary records so that equal scores and payload comparison are visible.
Compare nlargest, sorted and max on the same records
Copy the four code blocks into one Python file in order and run it. The first block defines six records, asks for three, and checks both the membership and ordering of the output. The 95-point records appear first, then cedar, the first 92-point record in input order. This is a deliberate tie at the boundary, not just a tie between two already-selected records.
For positive K and consistently ordered keys, nlargest has the result semantics of sorting descending and taking the first K. Python’s sort is stable even in descending order. If fewer than K records exist, the selection returns what is available. The result contains the original records, so a key function can read an integer score while preserving the fields you need in the report.
The example uses max only because one winner is enough in that branch. When the input may be empty, decide what absence means; default=None is suitable if your records cannot themselves be None. Check for that default before indexing the result. With nlargest or a sort and slice, an empty input yields an empty result.
| Need | Start with | Reason to switch |
|---|---|---|
| One record | max | Use a list-returning operation if the caller requires a list |
| A few records in ranked order | heapq.nlargest | Measure if K is a large share of the input |
| Full ranking or many prefixes | sorted | Retain only winners if memory is the constraint |
| All ties at the boundary | Explicit threshold policy | Output can grow beyond K |
from heapq import nlargest, nsmallest
from operator import itemgetter
rows = [
{"id": "cedar", "score": 92},
{"id": "birch", "score": 95},
{"id": "ash", "score": 92},
{"id": "elm", "score": 85},
{"id": "fir", "score": 95},
{"id": "alder", "score": 92},
]
score = itemgetter("score")
ids = lambda selected: [row["id"] for row in selected]
top = nlargest(3, rows, key=score)
assert ids(top) == ["birch", "fir", "cedar"]
assert top == sorted(rows, key=score, reverse=True)[:3]
assert ids(nlargest(10, rows, key=score)) == [
"birch", "fir", "cedar", "ash", "alder", "elm"
]
assert max(rows, key=score, default=None)["id"] == "birch"
print(ids(top))Source: Python 3.12 heapq: nlargest, nsmallest and priority queues ↗
A stable result depends on the input order you give it
Input order is a valid tie policy when it represents an event sequence. It is a weak policy when rows arrive in arbitrary order from a database query or a merge of concurrent sources. Stable sorting does not create stable source order. If a report must select the same records after the input is reshuffled, supply a unique and stable secondary key.
The first check below uses nsmallest with a key of negative score followed by ID. Negating the score makes higher scores sort first while the ID remains ascending. Reversing a key of (score, ID) would reverse both fields, which is a different policy. The second check retains every record whose score reaches the cutoff, producing five records for a request that began with three.
The inclusive example rereads a small in-memory collection. A one-pass stream cannot generally emit all cutoff ties with a fixed K-sized result buffer: an arbitrary number of records can share the eventual cutoff. Choose a replayable input, a spool, an output limit that changes the contract, or an exact-K policy. Also decide separately whether duplicate IDs are allowed; none of the selection functions deduplicates them.
# Exact K: higher score first, then ascending stable ID.
by_id = nsmallest(3, rows, key=lambda row: (-row["score"], row["id"]))
assert ids(by_id) == ["birch", "fir", "alder"]
# All scores at the cutoff: the result may contain more than K rows.
cutoff = top[-1]["score"] # the fixture has at least three rows
including_ties = [
row for row in sorted(rows, key=score, reverse=True)
if row["score"] >= cutoff
]
assert ids(including_ties) == ["birch", "fir", "cedar", "ash", "alder"]Source: Python 3.12 sorting techniques: stable sorting and key functions ↗
Keep the input lazy without expecting an early answer
An iterable such as a generator can supply records without a prebuilt list. For exact top K on an unsorted finite source, the last row can still displace a winner. The selection has to examine the input to know that it is finished. A small result reduces the amount you need to keep, not the number of records you must read.
The counter below shows every row was visited. Reusing the same generator for a timing comparison or a fallback sort would compare against an exhausted input. Recreate the generator from the same source, or retain a snapshot if you can afford it. For a live feed with no end, define a window, a stopping rule, or periodic snapshots before asking for a final result.
Lazy input does not make the rest of a pipeline memory bounded. If a parser loads the full file before yielding records, or the caller first wraps the source in list(), the program already paid that cost. Inspect the entire data path when memory is the reason to switch.
seen = []
def stream():
for row in rows:
seen.append(row["id"])
yield row
source = stream()
assert nlargest(3, source, key=score) == top
assert seen == ids(rows) # even the non-winners were examined
assert list(source) == [] # source is exhausted
assert nlargest(3, stream(), key=score) == top # fresh sourceSee exactly why a bounded min-heap keeps the winners
For the teaching implementation below, the root is the worst currently retained record. While there are fewer than K entries, insert a new record. Once the heap is full, compare the candidate to that root and replace it only when the candidate is better. A smaller record cannot improve the winners, and removing the weakest winner makes room for a better one.
The priority pair is (score, negative arrival index). A later equal score has a smaller priority pair, so it loses to an earlier equal score when only one can remain. The arrival index is unique, which keeps comparisons from reaching the dictionary payload. Using only (score, record) can instead make equal scores trigger a comparison between dictionaries.
The heap is only partially ordered. Its root is useful for deciding what to replace, but reading the backing list does not produce a ranked report. Sort the retained entries before returning them. The code retains at most K entries, and only accepted candidates need heap maintenance once full. That explicit bound belongs to this implementation, not to every library version or every part of the caller’s pipeline.
This helper validates K and integer scores as its own contract. Zero returns immediately without consuming the input, and negative or non-integer K is rejected. It reads the score at arrival and returns references to the original records; keep scores and records unchanged during selection or provide snapshots when mutation is possible. The four blocks were executed together on Python 3.12.14.
from heapq import heappush, heapreplace
def top_k_int_scores(records, k):
if type(k) is not int or k < 0:
raise ValueError("k must be a non-negative integer")
if k == 0:
return []
kept = []
for index, row in enumerate(records):
value = row["score"]
if type(value) is not int:
raise ValueError("score must be an integer")
entry = (value, -index, row)
if len(kept) < k:
heappush(kept, entry)
elif entry[:2] > kept[0][:2]:
heapreplace(kept, entry)
return [row for _, _, row in sorted(kept, reverse=True)]
assert top_k_int_scores(iter(rows), 3) == top
assert top_k_int_scores(iter(rows), 10) == nlargest(10, rows, key=score)
assert top_k_int_scores([], 3) == []
unread = iter(rows)
assert top_k_int_scores(unread, 0) == []
assert next(unread) is rows[0]
print("PASS: heap selection matches the stable top-K contract")Source: Python 3.12 heapq: nlargest, nsmallest and priority queues ↗
Measure the real choice when the input is large
For N records, the teaching heap uses at most min(K, N) candidate entries. Under constant-cost comparisons, a replacement costs logarithmic time in the heap size, and the final sort touches only the retained records. Full sorting returns a materialized list of the input before slicing. These are useful distinctions, but they do not imply a universal crossover point.
When K approaches N, maintaining a heap and then sorting much of it can lose the advantage of selecting a small subset. Sorting can also benefit from order already present in the data. An expensive key function, input parsing or slow storage can dominate both approaches. Prefer the library function in real code unless you need a custom contract such as maintaining a running heap for later snapshots.
To compare in your workload, first assert that both methods return the same IDs in the same order. Use fresh equivalent inputs for each run, try a few K values and tie densities, and record both elapsed time and peak memory. Decide whether opening the source and parsing belong in the timing, and apply that choice consistently. The correctness lab above does not claim a throughput improvement.
Source: Python 3.12 sorting techniques: stable sorting and key functions ↗
Use the symptom to find the broken contract
If a winner changes between runs, compare both the cutoff score and tie policy before blaming the heap. If a heap result looks unsorted, check whether the caller sorted the retained entries. If the second run is empty, test whether the input is one-shot. If memory is still high, look for materialization upstream and retained results downstream.
Keep score keys in one comparable domain. For a production pipeline that accepts missing values, mixed types or NaN, define validation and missing-score policy before ranking. Do not silently replace a missing score with zero if negative scores are valid. Tests should include an empty source, fewer than K records, all equal scores and a tie that straddles the cutoff.
Start with nlargest when a small, exact result is the whole task. Move to full sorting when you actually need a full order, and make deterministic tie-breaking explicit when input order has no business meaning. Use a bounded heap when its state is part of the problem you need to control.
Your next steps
- Exact K and all ties at the cutoff are different output contracts.
- A small top-K result still requires reading the entire unsorted finite input.
- A bounded min-heap retains candidates; sort those candidates to produce a ranked list.
Sources & official resources
Linked resources checked on 2026-11-07. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →