Python: take max N elements from some list

Albert picture Albert · Nov 18, 2010 · Viewed 36.3k times · Source

Is there some function which would return me the N highest elements from some list?

I.e. if max(l) returns the single highest element, sth. like max(l, count=10) would return me a list of the 10 highest numbers (or less if l is smaller).

Or what would be an efficient easy way to get these? (Except the obvious canonical implementation; also, no such things which involve sorting the whole list first because that would be inefficient compared to the canonical solution.)

Answer

Gareth Rees picture Gareth Rees · Nov 18, 2010

heapq.nlargest:

>>> import heapq, random
>>> heapq.nlargest(3, (random.gauss(0, 1) for _ in xrange(100)))
[1.9730767232998481, 1.9326532289091407, 1.7762926716966254]