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 List methods
Python list methods are built-in functions that allow us to perform various operations on lists, such as adding, removing, or modifying elements. In this article, weâll explore all Python list methods with a simple example. List MethodsLet's look at different list methods in Python: append(): Adds a
3 min read
Python | Pandas DataFrame.nlargest()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas nlargest() method is used to get n largest values from a data frame or a series
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: [GFGTABS] Python a = [2,3,6,1,8,4,9,0] print(max(a)) [/GFGTABS]Output9 Syntaxmax(listname) Parameter: listname : Name of list in which we have to find
4 min read
Python - __lt__ magic method
Python __lt__ magic method is one magic method that is used to define or implement the functionality of the less than operator "<" , it returns a boolean value according to the condition i.e. it returns true if a<b where a and b are the objects of the class. Python __lt__ magic method Syntax S
2 min read
Python Tuple - min() Method
While working with tuples many times we need to find the minimum element in the tuple, and for this, we can also use min(). In this article, we will learn about the min() method used for tuples in Python. Syntax of Tuple min() MethodSyntax: min(object) Parameters: object: Any iterable like Tuple, Li
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() wo
3 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 quotati
6 min read
Python string capwords() method
capwords() method in Python is a part of the string module and is used to capitalize the first letter of every word in a given string while converting all other letters to lowercase. To use capwords(), the string module must be imported as it is not a built-in string method. [GFGTABS] Python import
3 min read
Python | Pandas Index.min()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.min() function returns the minimum value of the Index. The function works
2 min read
Python List sort() Method
The sort() method in Python is a built-in function that allows us to sort the elements of a list in ascending or descending order and it modifies the list in place which means there is no new list created. This method is useful when working with lists where we need to arranged the elements in a spec
4 min read