Retrieve the n largest values, optionally by a key.
What You Will Learn
nlargest(n, iterable, key=None) returns a list of the highest values. Its efficiency depends on n relative to the input size; sorted() can be preferable when requesting most elements.
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.
from heapq import nlargest
scores = {'Ava': 70, 'Leo': 94, 'Mia': 88}
print(nlargest(2, scores, key=scores.get))
How the Example Works
- The imports provide the standard-library tools used in the demonstration: heapq.
- The variable scores holds the result of {'Ava': 70, 'Leo': 94, 'Mia': 88}. 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 nlargest(2, scores, key=scores.get) prints ['Leo', 'Mia']. Compare that result with the rule above before you change the argument.
Expected output from the example:
['Leo', 'Mia']
Another Example: Compare the Results
Try a second input and compare it with the first. Notice whether the result changes in type, value, order, or number of items.
from heapq import nlargest
print(nlargest(2, [3, 9, 1, 5]))
Expected output:
[9, 5]
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
Find the three largest sales transactions.
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
- Forgetting that nlargest() returns original elements rather than the evaluated key values.
- Assuming the input is correctly sorted or arranged without checking the algorithm’s preconditions.
Key Takeaways
- Retrieve the n largest values, optionally by a key.
- nlargest(n, iterable, key=None) returns a list of the highest values.
- Apply this operation only after checking the assumptions and input conditions shown in the example.