# Python: Getting Largest or Smallest n items of an Iterable

Getting Largest or Smallest n items of an Iterable in Python

## Getting Largest or Smallest n items of an Iterable in Python

Getting Largest or Smallest n items of an Iterable: Python's standard library heapq is an implementation of the heap queue algorithm, or the priority queue algorithm. Using its nsmallest() and nlargest() functions, you can obtain the largest or smallest n items of an iterable.

## Getting Largest or Smallest n items of an Iterable

```>>> import heapq
>>> smallestFour = heapq.nsmallest(4, range(10))
>>> smallestFour
[0, 1, 2, 3]
>>> largestThree = smallestFour = heapq.nlargest(3, range(10))
>>> largestThree
[9, 8, 7]

# Both nsmallest() and nlargest() functions provide an optional argument called key, with which you can provide the criteria of comparing items. This can be facilitated using lambda expressions or anonymous functions.
>>> records = [
{'name': 'Ethan', 'rollNo': 1},
{'name': 'Matty', 'rollNo': 2},
{'name': 'Jenna', 'rollNo': 3},
{'name': 'Haley', 'rollNo': 4},
{'name': 'Nathan', 'rollNo': 5}
]
>>> topThree = heapq.nsmallest(3, records, key = lambda records: records['rollNo'])
>>> topThree
[{'name': 'Ethan', 'rollNo': 1}, {'name': 'Matty', 'rollNo': 2}, {'name': 'Jenna', 'rollNo': 3}]
>>> lastTwo = heapq.nlargest(2, records, key = lambda records: records['rollNo'])
>>> lastTwo
[{'name': 'Nathan', 'rollNo': 5}, {'name': 'Haley', 'rollNo': 4}]
```