Python heapq.nlargest() Method
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)
Output3 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)
Output3 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)
Output3 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.
Similar Reads
Python heapq.nsmallest() Method
The heapq.nsmallest() method in Python is part of the heapq module and is used to retrieve the n smallest elements from an iterable, such as a list, tuple or other iterable objects. This method is highly useful when you need to efficiently find the smallest elements in a dataset, without sorting the
4 min read
Python | Decimal min() method
Decimal#min() : min() is a Decimal class method which compares the two Decimal values and return the min of two. Syntax: Decimal.min() Parameter: Decimal values Return: the min of two. Code #1 : Example for min() method Python3 # Python Program explaining # min() method # loading decimal library fro
2 min read
Python List max() Method
max() function in Python is a built-in function that finds and returns the largest element from the list. Let's understand it better with an example:Pythona = [2,3,6,1,8,4,9,0] print(max(a))Output9 Syntaxmax(listname)Parameter:listname : Name of list in which we have to find the maximum value.Return
4 min read
Python | Decimal max() method
Decimal#max() : max() is a Decimal class method which compares the two Decimal values and return the max of two. Syntax: Decimal.max() Parameter: Decimal values Return: the max of two. Code #1 : Example for max() method Python3 # Python Program explaining # max() method # loading decimal library fro
2 min read
Python - String min() method
The min() function in Python is a built-in function that returns the smallest item in an iterable or the smallest of two or more arguments. When applied to strings, it returns the smallest character (based on ASCII values) from the string.Let's start with a simple example to understand how min() wor
2 min read
Python String max() Method
The string max() method returns the largest character in a string based on its Unicode value.Example:Pythons = "hello" res = max(s) print(res)Outputo Explanation: In string "hello", the unicode values of the characters are compared and the character 'o' has the highest Unicode value.Syntax of string
2 min read
Python | numpy.lookfor() method
With the help of numpy.lookfor() method, we can get the information about the module in the numpy by using numpy.lookfor() method. Syntax : numpy.lookfor(module_name) Return : Return the information about the module. Example #1 : In this example we can see that by using numpy.lookfor() method, we ar
1 min read
Python String Methods
Python string methods is a collection of in-built Python functions that operates on strings.Note: Every string method in Python does not change the original string instead returns a new string with the changed attributes. Python string is a sequence of Unicode characters that is enclosed in quotatio
5 min read
Python Program to Find Largest Element in an Array
To find the largest element in an array, iterate over each element and compare it with the current largest element. If an element is greater, update the largest element. At the end of the iteration, the largest element will be found. Given an array, find the largest element in it. Input : arr[] = {1
4 min read
Python | Decimal is_qnan() method
Decimal#is_qnan() : is_qnan() is a Decimal class method which checks whether the Decimal value is quite NaN value. Syntax: Decimal.is_qnan() Parameter: Decimal values Return: true - if the Decimal value is quite NaN value; otherwise false Code #1 : Example for is_qnan() method Python3 # Python Progr
2 min read