Find n largest and smallest number in an iterable

Python has sorted function which sorts iterable in ascending or descending order. # Sort descending In [95]: sorted([1, 2, 3, 4], reverse=True) Out[95]: [4, 3, 2, 1] # Sort ascending In [96]: sorted([1, 2, 3, 4], reverse=False) Out[96]: [1, 2, 3, 4] sorted(iterable, reverse=True)[:n] will yield first n largest numbers. There is an alternate way. Python has heapq which implements heap datastructure. heapq has function nlargest and nsmallest which take arguments n number of elements, iterable like list, dict, tuple, generator and optional argument key. [Read More]