Open In App

Python heapq.nlargest() Method

Last Updated : 17 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The heapq.nlargest() method in Python is a useful function from the heapq module that returns the n largest elements from an iterable, such as a list or tuple. This method is particularly handy when we want to quickly find the largest elements from a dataset, using a heap-based approach.

Basic Example of Finding the n Largest Elements:

Python
import heapq

# A list of numbers
a = [1, 3, 5, 7, 9, 2]

# Get the 3 largest numbers
largest = heapq.nlargest(3, a)

print("3 Largest numbers:", largest)

Output
3 Largest numbers: [9, 7, 5]

Explanation: The function returns the 3 largest numbers from the list, which are [9, 7, 5], sorted in descending order.

Syntax of nlargest() method

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

Parameters

  • n: The number of largest elements to retrieve.
  • iterable: The iterable (like a list or tuple) from which you want to extract the largest elements.
  • key (optional): A function that serves as a key for comparing elements. If not specified, the elements themselves are compared.

Return Value

The heapq.nlargest() method returns a list containing the n largest elements from the iterable, sorted in descending order. The elements are chosen based on their value, and you can specify a key function to customize how the largest elements are selected (similar to sorting).

How Does heapq.nlargest() Work?

Internally, the heapq.nlargest() method uses a heap to efficiently find the largest elements in the iterable. It operates with a time complexity of O(n log k), where n is the total number of elements in the iterable, and k is the number of largest elements requested. This makes heapq.nlargest() more efficient than sorting the entire iterable when only a few largest elements are needed.

Examples of nlargest() method

1. Using heapq.nlargest() with a Custom Key Function

We can use the key parameter to retrieve the largest elements based on custom criteria. For example, let's find the largest numbers based on their absolute values.

Python
import heapq

# A list of numbers, including negative values
a = [-10, 3, -5, 8, -2]

# Get the 3 largest numbers by absolute value
largest = heapq.nlargest(3, a, key=abs)

print("3 Largest numbers by absolute value:", largest)

Output
3 Largest numbers by absolute value: [-10, 8, -5]

Explanation: The key=abs argument makes the function consider the absolute value of each number while selecting the largest ones. So, -10 is chosen because it has the largest absolute value, followed by 8 and -5.

2. Using heapq.nlargest() with a List of Tuples

We can also use heapq.nlargest() with complex objects like tuples or dictionaries, where we can specify which field to use for comparison.

Python
import heapq

# List of tuples (priority, task)
a = [(2, "Task A"), (1, "Task B"), (3, "Task C"), (5, "Task D"), (4, "Task E")]

# Get the 3 tasks with the highest priority (highest priority value)
maxi = heapq.nlargest(3, a, key=lambda x: x[0])

print("3 Highest priority tasks:", maxi)

Output
3 Highest priority tasks: [(5, 'Task D'), (4, 'Task E'), (3, 'Task C')]

Explanation: Here, the key=lambda x: x[0] specifies that the largest elements should be based on the first item in each tuple, which represents the priority. The function returns the 3 tasks with the highest priority.

When to Use heapq.nlargest()?

You should use heapq.nlargest() when we need to efficiently retrieve the n largest elements from an iterable, especially when the list is large and we don't want to sort the entire dataset. Some use cases include:

  • Finding the top N elements: For example, when we want to find the top N highest salaries in a list of employees.
  • Priority queues: When dealing with priority queues where we need to get the largest (or smallest) elements quickly.
  • Efficient sorting: When sorting a large list but only interested in the largest elements, rather than sorting the entire list.

Next Article
Practice Tags :

Similar Reads