![]() |
VOOZH | about |
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.
[9, 7, 5]
Explanation: heapq.nlargest(3, a) returns the three largest values from a in descending order.
heapq.nlargest(n, iterable, key=None)
Parameters:
Return Value: Returns a list containing the n largest elements in descending order.
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:
Example 1: This example retrieves the four largest values from a list. The returned values are automatically arranged in descending order.
[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.
[-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.
[(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).
Use heapq.nlargest() when you need only the top largest elements from a collection. Common use cases include: