PYTHON
Finding N-Largest or N-Smallest Items Efficiently with `heapq`
Master Python's `heapq` module to efficiently find the N largest or smallest items from a collection without fully sorting, ideal for large datasets.
import heapq
numbers = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
# Find the 3 largest items
largest_three = heapq.nlargest(3, numbers)
print(f"3 largest numbers: {largest_three}") # Output: 3 largest numbers: [42, 37, 23]
# Find the 4 smallest items
smallest_four = heapq.nsmallest(4, numbers)
print(f"4 smallest numbers: {smallest_four}") # Output: 4 smallest numbers: [-4, 2, 2, 7]
# Example with a list of dictionaries (sorting by a specific key)
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
# Find the 2 most expensive stocks by price
most_expensive = heapq.nlargest(2, portfolio, key=lambda s: s['price'])
print("
2 most expensive stocks:")
for stock in most_expensive:
print(stock)
# Output:
# 2 most expensive stocks:
# {'name': 'AAPL', 'shares': 50, 'price': 543.22}
# {'name': 'ACME', 'shares': 75, 'price': 115.65}
# Find the 3 stocks with the fewest shares
fewest_shares = heapq.nsmallest(3, portfolio, key=lambda s: s['shares'])
print("
3 stocks with fewest shares:")
for stock in fewest_shares:
print(stock)
# Output:
# 3 stocks with fewest shares:
# {'name': 'HPQ', 'shares': 35, 'price': 31.75}
# {'name': 'YHOO', 'shares': 45, 'price': 16.35}
# {'name': 'AAPL', 'shares': 50, 'price': 543.22}
How it works: The `heapq` module implements the heap queue algorithm, also known as the priority queue algorithm. It's useful when you need to find the N largest or N smallest items from a collection without sorting the entire collection, which can be inefficient for very large datasets. `heapq.nlargest()` and `heapq.nsmallest()` functions take two arguments: the number N and the iterable. An optional `key` argument, similar to `sorted()`, can be provided to specify how to extract a comparison value from each element, enabling sorting of complex data structures like lists of dictionaries based on a specific field.