Python find largest N (top N) or smallest N items

Python examples to find the largest (or the smallest) N elements from a collection of elements using nlargest() and nsmallest() functions from heapq library.

1. Using heapq module’s nlargest() and nsmallest()

Python heapq module can be used to find N largest or smallest items from collections. It has two functions to help with –

  1. nlargest()
  2. nsmallest()

1.1. Find items in simple iterables

>>> import heapq

>>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]

print(heapq.nlargest(3, nums))  
>>> [42, 37, 23]

print(heapq.nsmallest(3, nums)) 
>>> [-4, 1, 2]

1.2. Find items in complex iterables

>>> portfolio = 
[
   {'name': 'IBM', 'shares': 100, 'price': 91.1},
   {'name': 'AAPL', 'shares': 50, 'price': 543.22},
   {'name': 'FB', 'shares': 200, 'price': 21.09},
   {'name': 'HPQ', 'shares': 35, 'price': 31.75},
   {'name': 'YHOO', 'shares': 45, 'price': 16.35},
   {'name': 'ACME', 'shares': 75, 'price': 115.65}
]

>>> cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
>> cheap
>>> [
		{'price': 16.35, 'name': 'YHOO', 'shares': 45}, 
		{'price': 21.09, 'name': 'FB', 'shares': 200}, 
		{'price': 31.75, 'name': 'HPQ', 'shares': 35}
	]

>>> expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
>>> expensive
>>> [
		{'price': 543.22, 'name': 'AAPL', 'shares': 50}, 
		{'price': 115.65, 'name': 'ACME', 'shares': 75}, 
		{'price': 91.1, 'name': 'IBM', 'shares': 100}
	]
If you are simply trying to find the single smallest or largest item (N=1), it is faster to use min() and max() functions.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode