Get indices of the top N values of a list

PythonList

Python Problem Overview


I have a list say a = [5,3,1,4,10]. I need to get indices of the top two values of the list, that is for 5 and 10 I would get [0, 4]. Is there a one-liner that Python offers for such a case?

Python Solutions


Solution 1 - Python

sorted(range(len(a)), key=lambda i: a[i])[-2:]

or

sorted(range(len(a)), key=lambda i: a[i], reverse=True)[:2]

or

import operator

zip(*sorted(enumerate(a), key=operator.itemgetter(1)))[0][-2:]

or (for long lists), consider using heapq.nlargest

zip(*heapq.nlargest(2, enumerate(a), key=operator.itemgetter(1)))[0]

Solution 2 - Python

Just a NumPy alternative:

import numpy as np

top_2_idx = np.argsort(a)[-2:]
top_2_values = [a[i] for i in top_2_idx]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhardikudeshiView Question on Stackoverflow
Solution 1 - PythonFred FooView Answer on Stackoverflow
Solution 2 - Pythonaikramer2View Answer on Stackoverflow