![]() |
VOOZH | about |
heapq.nsmallest() method returns the n smallest elements from an iterable. It is useful when you need only a few smallest values without sorting the entire collection.
Example: The following example retrieves the 3 smallest values from a list.
[1, 2, 3]
Explanation: heapq.nsmallest(3, a) returns the 3 smallest elements from a in ascending order.
heapq.nsmallest(n, iterable, key=None)
Parameters:
Return Value: Returns a list containing the n smallest elements in ascending order.
heapq.nsmallest() returns the n smallest elements from an iterable using a heap internally. It is efficient when you only need a few smallest elements instead of sorting the entire collection.
Time Complexity: O(n log k), where:
Example 1: This example retrieves the 4 smallest values from a list of numbers. The returned elements are automatically sorted in ascending order.
[3, 5, 8, 12]
Explanation: heapq.nsmallest(4, a) returns the four smallest elements from a.
Example 2: This example finds the 3 smallest numbers based on their absolute values. The key parameter controls how elements are compared.
[-2, 3, -5]
Explanation: key=abs compares elements using their absolute values, so -2, 3, and -5 have the smallest magnitudes.
Example 3: This example uses tuples where the first value represents priority. Tasks with the smallest priority values are selected.
[(1, 'Task A'), (2, 'Task B')]
Explanation: key=lambda x: x[0] tells heapq.nsmallest() to compare tuples using their priority value (first element).
Use heapq.nsmallest() when you need only the smallest elements from a collection. Common use cases include: