The nsmallest function of the heapq module in Python returns the specified number of smallest elements from a Python iterable. The nsmallest function also accepts a function as parameter which returns a comparison key to be used in sorting.
The nsmallest() method of the Python module heapify returns the specified number of smallest elements from an iterable in sorted order.
A key function can be passed as an argument to the nsmallest() function. The key function accepts one parameter and returns the comparison key to be used in the sorting process.
Using a key function helps sorting records based on a specific field where elements are actually objects or records with several attributes or fields.
Example
python
# Example Python program that uses heapq.nsmallest()
# function to find the n smallest elements from an iterable
import heapq
select = 4
elements = (2, 9, 17, 11, 6, 16, 8)
smallests = heapq.nsmallest(select, elements)
print(smallests)
Output
Output
[2, 6, 8, 9]
Example – Finding ‘n’ smallest elements using the key function
python
# Example Python program that uses heapq.nsmallest()
# along with a function that produces comparison keys
import heapq
# Key function returning the total scores
def total(result):
return result.math + result.physics + result.physics + result.physics
# Class defining Objects representing records of exam results
class ExamResult:
def __init__(self, id, math, physics, chemistry, biology):
self.id = id
self.math = math
self.physics = physics
self.chemistry = chemistry
self.biology = biology
def __str__(self):
return "%d"%self.id
# ExamResult objects
r1 = ExamResult(11, 55, 60, 75, 65)
r2 = ExamResult(12,95, 80, 76, 78)
r3 = ExamResult(13, 50, 65, 60, 85)
r4 = ExamResult(14, 55, 57, 50, 75)
# Find the lowest total scores
lowest = heapq.nsmallest(2, [r1, r2, r3, r4], key=total)
for result in lowest:
print(result)
Output
Output
14
11
Your privacy choices
We'd like to use Google Analytics cookies to count visits and see which tutorials are useful.
They are only set if you accept. We don't use advertising cookies and we don't sell your data.
You can change your choice any time from “Your privacy choices” at the bottom of every page.
Privacy Policy
Your privacy choices
Your browser sent a Global Privacy Control signal, so analytics is off unless you turn it on here.
Strictly necessary
Remembers this choice in your browser. No cookies, nothing sent to anyone.Always on