# How to Find N Largest or Smallest value in Python

Spread the love

## Problem –

You want to find N largest or smallest value from a collection in Python.

## Solution –

There are various ways to tackle this problem but the easiest one is using the nlargest() and nsmallest() from the heapq module.

In [18]: import heapq

In [19]: nums = [26, 98, 45, 10, 55, 78, 9, 4]

In [20]: # get 3 smallest values

In [21]: heapq.nsmallest(3, nums)
Out[21]: [4, 9, 10]

In [22]: # get 3 highest values

In [23]: heapq.nlargest(3, nums)
Out[23]: [98, 78, 55]

Both these functions has a key parameter that you can use find n smallest and largest value from a complicated data structure.

In [25]: fruit_prices = [
...:     {'name': 'banana','price':20},
...:     {'name':'apple','price':120},
...:     {'name':'coconut','price':50},
...:     {'name':'orange', 'price':80},
...:     {'name':'papaya','price':30},
...:     {'name':'strawberry','price':130}]

In [26]: # get 3 cheapest fruits

In [27]: heapq.nsmallest(3, fruit_prices, key= lambda x: x['price'])
Out[27]:
[{'name': 'banana', 'price': 20},
{'name': 'papaya', 'price': 30},
{'name': 'coconut', 'price': 50}]

In [28]: # get 3 expensive fruits

In [29]: heapq.nlargest(3, fruit_prices, key= lambda x: x['price'])
Out[29]:
[{'name': 'strawberry', 'price': 130},
{'name': 'apple', 'price': 120},
{'name': 'orange', 'price': 80}]


Rating: 1 out of 5.