How to Find N Smallest and Largest Items in Python Using HeapQ?

  • Post author:
  • Post category:Python
  • Reading time:1 mins read

Here is a Python program to find N smallest and largest items in a list using heapq.

Find N Smallest and Largest Items Using HeapQ in Python

import heapq

portfolio = [
   {'name': 'APPLE', 'pieces': 100, 'price': 92.1},
   {'name': 'MANGO', 'pieces': 50, 'price': 542.22},
   {'name': 'GRAPES', 'pieces': 200, 'price': 22.09},
   {'name': 'BANANA', 'pieces': 35, 'price': 34.75},
   {'name': 'PAPAYA', 'pieces': 45, 'price': 15.35},
   {'name': 'PEACH', 'pieces': 75, 'price': 118.65}

cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])



[{'name': 'PAPAYA', 'pieces': 45, 'price': 15.35}, {'name': 'GRAPES', 'pieces': 200, 'price': 22.09}, {'name': 'BANANA', 'pieces': 35, 'price': 34.75}]
[{'name': 'MANGO', 'pieces': 50, 'price': 542.22}, {'name': 'PEACH', 'pieces': 75, 'price': 118.65}, {'name': 'APPLE', 'pieces': 100, 'price': 92.1}]

Process finished with exit code 0

See also:

Vinish Kapoor

An Oracle Apex Consultant, Oracle ACE, and founder of and a question and answer forum for developers.