Heapq (nlargest or nsmalles)

If we need only the n largest or smallest element from a list, then instead of sorting it and get the top 3, the better solution is to use the heap nlargest / nsmallest. We will show the time complexity of both now,

# len(arr) = M
# Need N largest

arr.sort(reverse=True)[:N] # M log M

import heapq
heapq.nlargest(N, arr) # M log N

Related Notes