Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

heapq.nlargest

Selects the largest items in descending comparison-key order.

Version: Python 3.14; repository image, production runtime not attested

Syntax

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

Selects the largest items in descending comparison-key order.

A count exceeding the input size returns every input item; zero selects nothing.

Select up to n original items, descending by key, for a leaderboard. Equal keys keep input order, including across the selection cutoff. key=len ranks 'bbb' and 'cc' before 'a'; the returned objects are those strings, not their lengths. Nonpositive n yields an empty list, and n above input size returns every item.

from heapq import nlargest
scores = [("a", 2), ("b", 8), ("c", 8)]
assert nlargest(1, scores, key=lambda row: row[1]) == [("b", 8)]
assert nlargest(10, [1, 2]) == [2, 1]
assert nlargest(-1, [3]) == []

Examples

import heapq
print(heapq.nlargest(2, ["a", "bbb", "cc"], key=len))
print(heapq.nlargest(0, [3, 5]))

Result

['bbb', 'cc']
[]

Select up to n original items, descending by key, for a leaderboard. Equal keys keep input order, including across the selection cutoff. key=len ranks 'bbb' and 'cc' before 'a'; the returned objects are those strings, not their lengths. Nonpositive n yields an empty list, and n above input size returns every item.

Sources