Heap Functions

heapq.nlargest()

Select up to n largest elements in descending key order; useful for small selections compared with the input size.

Formal Syntax & Structure

python syntaxpython
heapq.nlargest(n, iterable, key=None)

Parameters & Attributes

NameTypeDescription
nintRequested count; see constraints in description.
iterableiterableInput values, consumed as needed.
keycallable or NoneOptional key function used for comparison or grouping.

Return Value

list

The list result described above.

Working Example

Example Snippetpython
import heapqprint(heapq.nlargest(2,[4,1,3,2]))
Python Reference