all Python 3heapqfunction
heapq.nsmallest()
selection
Return a list of the n smallest items in ascending order; accepts key= like sorted(). For n=1 plain min() is cheaper.
Syntax
heapq.nsmallest(n, iterable, key=None)
The argument need not be a heap and the heap invariant is not used: any iterable works and the function builds its own internal structure. So calling it on a list you already maintain as a heap buys nothing — the minimum is sitting in heap[0] at O(1). As with sorted(), key is applied once per element, so an expensive key function is not recomputed during comparisons.
Examples
import heapq
data = [3, 1, 4, 1, 5, 9, 2, 6]
heapq.nsmallest(3, data) # → [1, 1, 2]
words = ['banana', 'kiwi', 'apple']
heapq.nsmallest(2, words, key=len) # → ['kiwi', 'apple']
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy