Largest and smallest items in a collection

suggest change

To find the largest items in a collection, the heapq module has a function called nlargest. We pass it two arguments. The first one is the number of items that we want to retrieve, and the second one is the collection name:

import heapq

numbers = [1, 4, 2, 100, 20, 50, 32, 200, 150, 8]
print(heapq.nlargest(4, numbers))  # [200, 150, 100, 50]

Similarly, to find the smallest items in a collection, we use the nsmallest function:

print(heapq.nsmallest(4, numbers))  # [1, 2, 4, 8]

Both nlargest and nsmallest functions take an optional argument (key parameter) for complicated data structures. The following example shows the use of the age property to retrieve the oldest and the youngest people from the people list:

people = [
    {'firstname': 'John', 'lastname': 'Doe', 'age': 30},
    {'firstname': 'Jane', 'lastname': 'Doe', 'age': 25},
    {'firstname': 'Janie', 'lastname': 'Doe', 'age': 10},
    {'firstname': 'Jane', 'lastname': 'Roe', 'age': 22},
    {'firstname': 'Johnny', 'lastname': 'Doe', 'age': 12},
    {'firstname': 'John', 'lastname': 'Roe', 'age': 45}
]

oldest = heapq.nlargest(2, people, key=lambda s: s['age'])
print(oldest)
# Output: [{'firstname': 'John', 'lastname': 'Roe', 'age': 45}, {'firstname': 'John', 'lastname': 'Doe', 'age': 30}]

youngest = heapq.nsmallest(2, people, key=lambda s: s['age'])
print(youngest)
# Output: [{'firstname': 'Janie', 'lastname': 'Doe', 'age': 10}, {'firstname': 'Johnny', 'lastname': 'Doe', 'age': 12}]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents