Skip to content
Related Articles

Related Articles

Python | Returning index of a sorted list
  • Last Updated : 11 May, 2020


Sort a list in python and then return the index of elements in sorted order.

Examples:

Input  : [2, 3, 1, 4, 5] 
Output : [2, 0, 1, 3, 4]
After sorting list becomes [1, 2, 3, 4, 5] 
and their index as [2, 0, 1, 3, 4]

Input  : [6, 4, 7, 8, 1]
Output : [4, 1, 0, 2, 3]
After sorting the list becomes [1, 4, 6, 7, 8] 
and their index as [4, 1, 0, 2, 3].

Method 1




import numpy
s = numpy.array([2, 3, 1, 4, 5])
sort_index = numpy.argsort(s)
print(sort_index)


Output :

[2, 0, 1, 3, 4]

Method 2






s = [2, 3, 1, 4, 5]
li=[]
  
for i in range(len(s)):
      li.append([s[i],i])
li.sort()
sort_index = []
  
for x in li:
      sort_index.append(x[1])
  
print(sort_index)


Output:

[2, 0, 1, 3, 4]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :