Python heapq.nlargest() Method (original) (raw)

Last Updated : 11 Jun, 2026

heapq.nlargest() function returns the n largest elements from an iterable. It is useful when you need only the largest values without sorting the entire dataset.

**Example: The following example returns the 3 largest elements from a list.

Python `

import heapq a = [1, 3, 5, 7, 9, 2] print(heapq.nlargest(3, a))

`

**Explanation: heapq.nlargest(3, a) returns the three largest values from a in descending order.

Syntax

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

**Parameters:

**Return Value: Returns a list containing the n largest elements in descending order.

Working of heapq.nlargest()

heapq.nlargest() returns the n largest elements from an iterable. It uses a heap internally, making it efficient when you only need a few largest elements instead of sorting the entire dataset.

**Time Complexity: O(n log k), where:

Examples

**Example 1: This example retrieves the four largest values from a list. The returned values are automatically arranged in descending order.

Python `

import heapq a = [12, 5, 18, 7, 25, 10] res = heapq.nlargest(4, a) print(res)

`

**Explanation: heapq.nlargest(4, a) selects the four highest values from a and returns them in descending order.

**Example 2: This example finds the three largest numbers based on their absolute values instead of their actual values.

Python `

import heapq a = [-10, 3, -5, 8, -2] res = heapq.nlargest(3, a, key=abs) print(res)

`

**Explanation: key=abs makes heapq.nlargest() compare elements using their absolute values rather than their original values.

**Example 3: This example retrieves the three tuples with the highest priority values from a list of (priority, task) pairs.

Python `

import heapq

a = [ (2, "Task A"), (1, "Task B"), (5, "Task C"), (4, "Task D"), (3, "Task E")] res = heapq.nlargest(3, a, key=lambda x: x[0]) print(res)

`

Output

[(5, 'Task C'), (4, 'Task D'), (3, 'Task E')]

**Explanation: key=lambda x: x[0] tells heapq.nlargest() to compare tuples using their first element (priority value).

When to Use heapq.nlargest()

Use heapq.nlargest() when you need only the top largest elements from a collection. Common use cases include: