HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Python / Python find largest N (top N) or smallest N items

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

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Python Examples

  • Python Hello World
  • Python Dictionary Intersection
  • Python Unpacking Tuple
  • Python Find Largest N Items
  • Python Finding Max and Min
  • Python Print to File
  • Python Print Without Newline
  • Python Print List

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces