Python | Returning index of a sorted list


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



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

[2, 0, 1, 3, 4]

Method 2

filter_none

edit
close

play_arrow

link
brightness_4
code

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)

chevron_right


Output:

[2, 0, 1, 3, 4]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.