Search code examples
pythonlistmaxsliceindices

In Python, how can I get the indices of the 5 greatest values of a list?


I have a simple list:

a = [8, 5, 2, 20, 13, 14, 17, 13, 15, 21]

I can get the 5 greatest values in the list:

sorted(a)[-5:]

How could I get the indices of the 5 greatest values in the list?

So, the 5 greatest values of the list are [14, 15, 17, 20, 21] and these are at indices [9, 3, 6, 8, 5]. I'm sure there are multiple strategies to consider if there are duplicate values one might be to give their indices if they are near to other great values.


Solution

  • You can try this:

    [x[0] for x in sorted(enumerate(a), key=lambda x: x[1])[-5:]]