Skip to content
Related Articles

Related Articles

Improve Article

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 reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :