# Nsmallest Function Of Heapq Module In Python

## Overview:

• 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:

 # 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:

 [2, 6, 8, 9]

## Example – Finding ‘n’ smallest elements using the key function:

 # 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)

 14 11