Its what that heapq.nsmallest
is for:
>>> import heapq
>>> l=[10, 12, 2, 2, 5 ,15]
>>> print(heapq.nsmallest(2, set(l))) [1]
5
Note that set(l)
is for remove duplicate indices ! (thank of Jon Clements for reminding in comment)
Also you can use sorted(iterable)[:n][1]
for find second smallest that sorted(iterable)[:n]
give you n smallest indices !
The most important feature of a heap is that heap[0]
is always the smallest item. More‐
over, subsequent items can be easily found using the heapq.heappop()
method, which
pops off the first item and replaces it with the next smallest item (an operation that
requires O(log N) operations where N is the size of the heap)
source code of nsmallest
def nsmallest(n, iterable):
"""Find the n smallest elements in a dataset.
Equivalent to: sorted(iterable)[:n]
"""
if n < 0:
return []
it = iter(iterable)
result = list(islice(it, n))
if not result:
return result
_heapify_max(result)
_heappushpop = _heappushpop_max
for elem in it:
_heappushpop(result, elem)
result.sort()
return result