Open In App

Python heapq.nsmallest() Method

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

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 entire collection. It uses the heap data structure to efficiently return the smallest elements.

Example: Finding the n Smallest Elements

Python
import heapq

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

# Get the 3 smallest numbers
smallest = heapq.nsmallest(3, a)

print("3 Smallest numbers:", smallest)

Output
3 Smallest numbers: [1, 2, 3]

Explanation: The function returns the 3 smallest numbers from the list, which are [1, 2, 3], sorted in ascending order.

Syntax of nlargest() method

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

Parameters

  • n: The number of smallest elements to retrieve.
  • iterable: The iterable (list, tuple, etc.) from which you want to extract the smallest elements.
  • key (optional): A function to specify the criteria for comparing elements. If not provided, the elements are compared directly.

Return Value

The heapq.nsmallest() method returns a list of the n smallest elements from the iterable, sorted in ascending order. The comparison is done using the key function (if provided) and the elements are selected based on their value.

How Does heapq.nsmallest() Work?

  • The heapq.nsmallest() method uses a heap-based approach to find the smallest elements, which is more efficient than sorting the entire 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 smallest elements requested. This makes it more efficient than sorting the entire dataset when you only need a few smallest elements.

Examples of nsmallest() method

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

You can use the key parameter to customize how the smallest elements are selected. For example, finding the smallest elements based on their absolute values.

Python
import heapq

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

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

print(smallest)

Output
[-2, 3, -5]

Explanation: The key=abs argument makes the function consider the absolute value of each number. So, -2 is chosen because it has the smallest absolute value, followed by 3 and -5.

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

heapq.nsmallest() can also be used with more complex structures like tuples. You can specify which element of the tuple to use for comparison.

Python
import heapq

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

# Get the 2 tasks with the lowest priority (lowest priority value)
b = heapq.nsmallest(2, a, key=lambda x: x[0])

print("2 Smallest tasks by priority:", b)

Output
2 Smallest tasks by priority: [(1, 'Task B'), (2, 'Task A')]

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

When to Use heapq.nsmallest()?

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

  • Finding the smallest N elements: For example, finding the smallest salaries in a company or the least expensive items in a store.
  • Priority Queues: When working with priority queues, where you need to retrieve the smallest (or highest priority) elements.
  • Efficient Sorting: If you need to get a few smallest elements, but don't need to sort the entire collection.
  • Task Scheduling: When tasks with deadlines or priorities are processed in order of urgency.

Next Article
Practice Tags :

Similar Reads