Trusted answers to developer questions

What are heapq::nsmallest() and heapq::nlargest() in Python?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

Python is a high-level programming language that provides a range of modules and functions. The heap structure is used to represent priority queues and comes with the heapq module. There is a multitude of methods that can be performed on these structures. The nsmallest() and nlargest() methods can be used to find the smallest and largest values in a heap, respectively.

Syntax

nsmallest(k, iterable, key = fun)
nlargest(k, iterable, key = fun)

Arguments

  1. k: Specifies the number of smallest/largest elements to be returned. This parameter is required.
  2. iterable: Specifies the iterable to extract the smallest/largest values from. This parameter is required.
  3. key (Optional): Specifies a function that has only one argument. If specified, a comparison key is extracted from each item in the iterable.

Return Value

The nsmallest() method returns k smallest values, while the nlargest() method returns k largest values in the iterable.

Code

#import library
import heapq
#initialize lists
list1=[5, 12, 93, 1, 53, 17, 9]
list2=[4.8, 9.2, 12.6, 47.3, 16.5]
#print lists
print('List 1:',list1)
print('List 2:',list2)
#print smallest values
print('3 smallest values of list 1:', heapq.nsmallest(3,list1))
print('2 smallest values of list 2:', heapq.nsmallest(2,list2))
#print largest values
print('3 largest values of list 1:', heapq.nlargest(3,list1))
print('2 largest values of list 2:', heapq.nlargest(2,list2))

RELATED TAGS

python
Did you find this helpful?