Skip to content
Related Articles
Open in App
Not now

Related Articles

Python | Returning index of a sorted list

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 16 Jan, 2023
Improve Article
Save Article

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 

Python




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

Output : 

[2, 0, 1, 3, 4]

Time Complexity: O(n*log(n))
Auxiliary Space: O(n)

Method 2 

Python




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]

Time Complexity: O(n*log(n))
Auxiliary Space: O(n)

Method #3: Using the built-in sorted() function along with enumerate() function
 

Python3




s = [2, 3, 1, 4, 5]
# Using the built-in sorted() function along with enumerate() function
# enumerate() returns a tuple (index, value) for each element in the list
# and sorted() sorts the list based on the value
sort_index = [i for i, x in sorted(enumerate(s), key=lambda x: x[1])]
print(sort_index)
#This code is contributed by Edula Vinay Kumar Reddy

Output

[2, 0, 1, 3, 4]

This method uses the built-in sorted() function which takes an iterable (in this case, the enumerate of the original list) and sorts it based on a key function (in this case, the lambda function that accesses the second element of each tuple returned by enumerate). The [i for i, x in …] list comprehension then iterates through the sorted enumerate and appends the first element (the index) of each tuple to the sort_index list.

Time Complexity: O(n*log(n))
Auxiliary Space: O(n)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!