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 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 - 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