VOOZH about

URL: https://www.geeksforgeeks.org/python/python-heapq-nsmallest-method/

⇱ Python heapq.nsmallest() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python heapq.nsmallest() Method

Last Updated : 11 Jun, 2026

heapq.nsmallest() method returns the n smallest elements from an iterable. It is useful when you need only a few smallest values without sorting the entire collection.

Example: The following example retrieves the 3 smallest values from a list.


Output
[1, 2, 3]

Explanation: heapq.nsmallest(3, a) returns the 3 smallest elements from a in ascending order.

Syntax

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

Parameters:

  • n: Number of smallest elements to return.
  • iterable: Collection of elements to search.
  • key (optional): Function used for custom comparison

Return Value: Returns a list containing the n smallest elements in ascending order.

Working of heapq.nsmallest()

heapq.nsmallest() returns the n smallest elements from an iterable using a heap internally. It is efficient when you only need a few smallest elements instead of sorting the entire collection.

Time Complexity: O(n log k), where:

  • n = total number of elements
  • k = number of smallest elements requested

Examples

Example 1: This example retrieves the 4 smallest values from a list of numbers. The returned elements are automatically sorted in ascending order.


Output
[3, 5, 8, 12]

Explanation: heapq.nsmallest(4, a) returns the four smallest elements from a.

Example 2: This example finds the 3 smallest numbers based on their absolute values. The key parameter controls how elements are compared.


Output
[-2, 3, -5]

Explanation: key=abs compares elements using their absolute values, so -2, 3, and -5 have the smallest magnitudes.

Example 3: This example uses tuples where the first value represents priority. Tasks with the smallest priority values are selected.


Output
[(1, 'Task A'), (2, 'Task B')]

Explanation: key=lambda x: x[0] tells heapq.nsmallest() to compare tuples using their priority value (first element).

When to Use heapq.nsmallest()

Use heapq.nsmallest() when you need only the smallest elements from a collection. Common use cases include:

  • Finding the lowest scores, prices, or salaries.
  • Retrieving the lowest-priority items from a dataset.
  • Getting a few smallest values from large datasets without sorting the entire collection.
Comment
Article Tags: