On this page
heapq.nsmallest
Prev: heapq.nlargest | Up: heapq
Rel: heapq.heapify, heapq.heapify_max, heapq.heappop, heapq.heappop_max
Ref: docs.python.org — heapq.nsmallest
Tags: #public #python3 #stdlib #heapq
Import
import heapq
from heapq import nsmallest
Signature & Overview
heapq.nsmallest(n, iterable, key=None)
Find the n smallest elements in a dataset.
Usage
import heapq
assert heapq.nsmallest(2, [5, 1, 9, 3, 7]) == [1, 3]
Gotchas
- Supports
key=: Fast for small $k$ without sorting the entire sequence.
REPL Inspect
from heapq import nsmallest
help(nsmallest)
Linked from
Related notes
- tuts/python3/stdlib_module/heapq/nlargest Linked here; links to this page; shared tags: #heapq, #stdlib
- tuts/python3/stdlib_module/heapq Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/heapq/heapify Linked here; shared tags: #heapq, #stdlib
- tuts/python3/stdlib_module/heapq/heapify_max Linked here; shared tags: #heapq, #stdlib
- tuts/python3/stdlib_module/heapq/heappop Linked here; shared tags: #heapq, #stdlib
- tuts/python3/stdlib_module/heapq/heappop_max Linked here; shared tags: #heapq, #stdlib
- tuts/python3/stdlib_module/heapq/heappush shared tags: #heapq, #stdlib
- tuts/python3/stdlib_module/heapq/heappush_max shared tags: #heapq, #stdlib
- tuts/python3/stdlib_module/heapq/heappushpop shared tags: #heapq, #stdlib
- tuts/python3/stdlib_module/heapq/heappushpop_max shared tags: #heapq, #stdlib