Last Updated : 17 Mar, 2025
The heapq.nsmallest() method in Python is part of the heapq module and is used to retrieve the n smallest elements from an iterable, such as a list, tuple or other iterable objects. This method is highly useful when you need to efficiently find the smallest elements in a dataset, without sorting the entire collection. It uses the heap data structure to efficiently return the smallest elements.
Example: Finding the n Smallest Elements
Python
import heapq
# A list of numbers
a = [1, 3, 5, 7, 9, 2]
# Get the 3 smallest numbers
smallest = heapq.nsmallest(3, a)
print("3 Smallest numbers:", smallest)
3 Smallest numbers: [1, 2, 3]
Explanation: The function returns the 3 smallest numbers from the list, which are [1, 2, 3], sorted in ascending order.
Syntax of nlargest() methodParametersheapq.nsmallest(n, iterable, key=None)
The heapq.nsmallest() method returns a list of the n smallest elements from the iterable, sorted in ascending order. The comparison is done using the key function (if provided) and the elements are selected based on their value.
How Does heapq.nsmallest() Work?You can use the key parameter to customize how the smallest elements are selected. For example, finding the smallest elements based on their absolute values.
Python
import heapq
# A list of numbers, including negative values
a = [-10, 3, -5, 8, -2]
# Get the 3 smallest numbers by absolute value
smallest = heapq.nsmallest(3, a, key=abs)
print(smallest)
Explanation: The key=abs argument makes the function consider the absolute value of each number. So, -2 is chosen because it has the smallest absolute value, followed by 3 and -5.
2. Using heapq.nsmallest() with a List of Tuplesheapq.nsmallest() can also be used with more complex structures like tuples. You can specify which element of the tuple to use for comparison.
Python
import heapq
# List of tuples (priority, task)
a = [(2, "Task A"), (1, "Task B"), (3, "Task C")]
# Get the 2 tasks with the lowest priority (lowest priority value)
b = heapq.nsmallest(2, a, key=lambda x: x[0])
print("2 Smallest tasks by priority:", b)
2 Smallest tasks by priority: [(1, 'Task B'), (2, 'Task A')]
Explanation: The key=lambda x: x[0] specifies that the smallest elements should be selected based on the first item in each tuple, which represents the priority. The function returns the 2 tasks with the lowest priority.
When to Use heapq.nsmallest()?You should use heapq.nsmallest() when you need to efficiently retrieve the n smallest elements from an iterable, especially when the list is large and you don't want to sort the entire dataset. Some common use cases include:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4