Advertisement
Advanced Python, Data Types & Structures

How would you choose between a list, a set, a dict, and a specialized structure like heapq for efficiently finding the K smallest/largest elements in a large dataset?

Short answer

heapq.nsmallest(k, iterable) or heapq.nlargest(k, iterable) is generally the most efficient choice for finding just K elements from a large dataset (O(n log k) rather than sorting the ENTIRE dataset at O(n log n) with sorted()[:k]) — a plain sort is simpler and fine for small…

Save Python mock interview
Advertisement
AModel answer
heapq.nsmallest(k, iterable) or heapq.nlargest(k, iterable) is generally the most efficient choice for finding just K elements from a large dataset (O(n log k) rather than sorting the ENTIRE dataset at O(n log n) with sorted()[:k]) — a plain sort is simpler and fine for small datasets, but heapq scales much better when the dataset is large and K is small relative to it.
import heapq

scores = [45, 92, 78, 12, 88, 67, 99, 34]
top_3 = heapq.nlargest(3, scores)
print(top_3)  # [99, 92, 88] -- more efficient than sorted(scores, reverse=True)[:3] for large datasets
Real-world example
Finding the top 10 highest-scoring results from a dataset of millions of records without fully sorting the entire dataset.
Likely follow-ups
  • At roughly what ratio of K to total dataset size does heapq's efficiency advantage over a full sort become negligible?
Related topics