How would you find the top N items in a large collection efficiently?

Python lists, dictionaries and sets · Experienced

Model answer

Use heapq.nlargest(n, items, key=...) or nsmallest, which are efficient when n is much smaller than the data size. Sorting everything costs O(m log m). For counting items use Counter.most_common(n).

Learn this topic

Dictionaries, Tuples and Sets in Python in the course Python for Beginners: Learn to Code with Real Projects.

Sign in to add your own answer.

More questions