heapq.nlargest() function returns the n largest elements from an iterable. It is useful when you need only the largest values without sorting the entire dataset.
Example: The following example returns the 3 largest elements from a list.
import heapq
a = [1, 3, 5, 7, 9, 2]
print(heapq.nlargest(3, a))
Output
[9, 7, 5]
Explanation: heapq.nlargest(3, a) returns the three largest values from a in descending order.
Syntax
heapq.nlargest(n, iterable, key=None)
Parameters:
- n: Number of largest elements to return.
- iterable: The collection of elements to search.
- key (optional): A function used to determine the comparison value.
Return Value: Returns a list containing the n largest elements in descending order.
Working of heapq.nlargest()
heapq.nlargest() returns the n largest elements from an iterable. It uses a heap internally, making it efficient when you only need a few largest elements instead of sorting the entire dataset.
Time Complexity: O(n log k), where:
- n = total number of elements
- k = number of largest elements requested
Examples
Example 1: This example retrieves the four largest values from a list. The returned values are automatically arranged in descending order.
import heapq
a = [12, 5, 18, 7, 25, 10]
res = heapq.nlargest(4, a)
print(res)
Output
[25, 18, 12, 10]
Explanation: heapq.nlargest(4, a) selects the four highest values from a and returns them in descending order.
Example 2: This example finds the three largest numbers based on their absolute values instead of their actual values.
import heapq
a = [-10, 3, -5, 8, -2]
res = heapq.nlargest(3, a, key=abs)
print(res)
Output
[-10, 8, -5]
Explanation: key=abs makes heapq.nlargest() compare elements using their absolute values rather than their original values.
Example 3: This example retrieves the three tuples with the highest priority values from a list of (priority, task) pairs.
import heapq
a = [ (2, "Task A"),
(1, "Task B"),
(5, "Task C"),
(4, "Task D"),
(3, "Task E")]
res = heapq.nlargest(3, a, key=lambda x: x[0])
print(res)
Output
[(5, 'Task C'), (4, 'Task D'), (3, 'Task E')]
Explanation: key=lambda x: x[0] tells heapq.nlargest() to compare tuples using their first element (priority value).
When to Use heapq.nlargest()
Use heapq.nlargest() when you need only the top largest elements from a collection. Common use cases include:
- Finding the top N highest scores, salaries, or marks.
- Retrieving the highest-priority items from a dataset.
- Getting the largest elements from large datasets without sorting the entire collection.