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.
import heapq
a = [1, 3, 5, 7, 9, 2]
res = heapq.nsmallest(3, a)
print(res)
Output
[1, 2, 3]
Explanation: heapq.nsmallest(3, a) returns the 3 smallest elements from a in ascending order.
Syntax
heapq.nsmallest(n, iterable, key=None)
Parameters:
- n: Number of smallest elements to return.
- iterable: Collection of elements to search.
- key (optional): Function used for custom comparison
Return Value: Returns a list containing the n smallest elements in ascending order.
Working of heapq.nsmallest()
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:
- n = total number of elements
- k = number of smallest elements requested
Examples
Example 1: This example retrieves the 4 smallest values from a list of numbers. The returned elements are automatically sorted in ascending order.
import heapq
a = [12, 5, 8, 20, 3, 15]
res = heapq.nsmallest(4, a)
print(res)
Output
[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.
import heapq
a = [-10, 3, -5, 8, -2]
res = heapq.nsmallest(3, a, key=abs)
print(res)
Output
[-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.
import heapq
a = [ (3, "Task C"),
(1, "Task A"),
(2, "Task B"),
(4, "Task D") ]
res = heapq.nsmallest(2, a, key=lambda x: x[0])
print(res)
Output
[(1, 'Task A'), (2, 'Task B')]
Explanation: key=lambda x: x[0] tells heapq.nsmallest() to compare tuples using their priority value (first element).
When to Use heapq.nsmallest()
Use heapq.nsmallest() when you need only the smallest elements from a collection. Common use cases include:
- Finding the lowest scores, prices, or salaries.
- Retrieving the lowest-priority items from a dataset.
- Getting a few smallest values from large datasets without sorting the entire collection.