heapq.nsmallest()
heapq.nsmallest() is a Python function in the Heapq Module category. Returns the n smallest elements from the iterable. The syntax is heapq.nsmallest(n, iterable, key=None). Returns: List of n smallest. A typical example: heapq.nsmallest(3, [5, 1, 9, 3, 7]) # [1, 3, 5]. A close sibling is heapq.heapify(), which transforms a list into a heap (min-heap), in-place, O(n) time. A close sibling is heapq.heappush(), which pushes an item onto the heap, maintaining the heap invariant. A close sibling is heapq.heappop(), which pops and returns the smallest item from the heap. A close sibling is heapq.heappushpop(), which pushes item then pops the smallest. More efficient than heappush then heappop. More about this category: Heap queue algorithm — heapify, heappush, heappop, nlargest. Related Heapq Module entries: heapq.heapify(), heapq.heappush(), heapq.heappop(), heapq.heappushpop(), heapq.heapreplace(), heapq.nlargest(). This page is part of the free Python Reference documentation covering 978+ functions, methods, and modules with examples and parameter details.