PYTHON

Efficiently Find N Smallest or Largest Items

Discover how to quickly find the N smallest or largest elements from any collection using Python's `heapq` module, ideal for ranking and top-k problems.

import heapq

data = [10, 4, 1, 8, 15, 6, 20, 3, 12]

# Find the 3 smallest elements
smallest_3 = heapq.nsmallest(3, data)
print(f"Original data: {data}")
print(f"3 smallest elements: {smallest_3}")

# Find the 4 largest elements
largest_4 = heapq.nlargest(4, data)
print(f"4 largest elements: {largest_4}")

# Using a key function for complex objects
items = [
    {'name': 'Laptop', 'price': 1200},
    {'name': 'Mouse', 'price': 25},
    {'name': 'Keyboard', 'price': 75},
    {'name': 'Monitor', 'price': 300},
    {'name': 'Webcam', 'price': 50},
]

# Find the 2 cheapest items
cheapest_2 = heapq.nsmallest(2, items, key=lambda x: x['price'])
print(f"2 cheapest items: {cheapest_2}")

# Find the 1 most expensive item
most_expensive_1 = heapq.nlargest(1, items, key=lambda x: x['price'])
print(f"1 most expensive item: {most_expensive_1}")
How it works: This snippet demonstrates the `heapq` module, specifically `nsmallest` and `nlargest`, for efficiently retrieving the N smallest or largest elements from a collection. These functions avoid fully sorting the entire dataset, which can be much more performant for large collections when only a few extreme values are needed. They also support a `key` argument for sorting complex objects based on a specific attribute.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs