Heap Functions
heapq.nsmallest()
Select up to n smallest elements in ascending key order; useful for small selections compared with the input size.
Formal Syntax & Structure
python syntaxpython
heapq.nsmallest(n, iterable, key=None)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| n | int | Requested count; see constraints in description. |
| iterable | iterable | Input values, consumed as needed. |
| key | callable or None | Optional key function used for comparison or grouping. |
Return Value
list
The list result described above.
Working Example
Example Snippetpython
import heapqprint(heapq.nsmallest(2,[4,1,3,2]))