Last Updated : 17 Mar, 2025
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)
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() methodParametersheapq.nlargest(n, iterable, key=None)
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?Examples of nlargest() method 1. Using heapq.nlargest() with a Custom Key FunctionInternally, 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.
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)
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 TuplesWe 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)
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:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4