Find a small number of extreme values with a heap instead of sorting everything.
What You Will Learn
heapq.nlargest and nsmallest can return the top k records using bounded auxiliary storage relative to k. They are helpful when k is small compared with the full input. A complete sort may be simpler or faster when you need most records in sorted order.
Time complexity assumes a specific input structure. Include setup work such as sorting or building a lookup table when comparing complete solutions.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
import heapq
products = [
{"name": "A", "sales": 12},
{"name": "B", "sales": 25},
{"name": "C", "sales": 18},
]
leaders = heapq.nlargest(2, products, key=lambda item: item["sales"])
print([item["name"] for item in leaders])
How the Example Works
- The imports provide the standard-library tools used in the demonstration: heapq.
- The variable products holds the result of [{'name': 'A', 'sales': 12}, {'name': 'B', 'sales': 25}, {'name': 'C', 'sales': 18}]. Later lines use that value or inspect how it changes.
- The variable leaders holds the result of heapq.nlargest(2, products, key=lambda item: item['sales']). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
For the chosen input, the expression [item['name'] for item in leaders] prints ['B', 'C']. Compare that result with the rule above before you change the argument.
Expected output from the example:
['B', 'C']
When You Would Use This
This technique matters when a program handles larger queues, sorted records, or repeated lookups. Choose the data structure based on actual operations and the preconditions the algorithm requires. Verify boundary inputs before optimizing for speed.
Practice: Modify the Code
Return the three lowest-priced items from a longer product collection.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Sorting a massive data source just to keep two records without evaluating top-k selection.
- Assuming heapq.nlargest produces a reusable lazy iterator instead of a result list.
Key Takeaways
- Find a small number of extreme values with a heap instead of sorting everything.
- heapq.nlargest and nsmallest can return the top k records using bounded auxiliary storage relative to k.
- Apply this operation only after checking the assumptions and input conditions shown in the example.