CKTIS / Python
heapq.nsmallest
Selects the smallest items in ascending comparison-key order.
Version: Python 3.14; repository image, production runtime not attested
Syntax
heapq.nsmallest(n, iterable, key=None)Selects the smallest items in ascending comparison-key order.
There may be fewer results than requested. Equal elements are retained as separate items.
For a shortlist of low values, nsmallest returns up to n original items ascending by key. The default compares the items themselves; ties keep their input order. Selecting three from [5, 2, 2, 8] keeps both 2s before 5. Requesting five from [7] returns just [7], and an empty source yields [].
from heapq import nsmallest
rows = [("A", 4), ("B", 1), ("C", 1), ("D", 2)]
assert nsmallest(2, rows, key=lambda r: r[1]) == [("B", 1), ("C", 1)]
assert nsmallest(0, rows) == [] and nsmallest(3, []) == []
Examples
import heapq
print(heapq.nsmallest(3, [5, 2, 2, 8]))
print(heapq.nsmallest(5, [7]))
Result
[2, 2, 5] [7]
For a shortlist of low values, nsmallest returns up to n original items ascending by key. The default compares the items themselves; ties keep their input order. Selecting three from [5, 2, 2, 8] keeps both 2s before 5. Requesting five from [7] returns just [7], and an empty source yields [].