Finding relative order of elements in list in Python


We are given a list whose elements are integers. We are required to find the relative order which means if they are sorted in ascending order then we need to find index of their positions.

With sorted and index

We first sort the entire list and then find out the index of each of them after the sorting.

Example

 Live Demo

listA = [78, 14, 0, 11]
# printing original list
print("Given list is : \n",listA)
# using sorted() and index()
res = [sorted(listA).index(i) for i in listA]
# printing result
print("list with relative ordering of elements : \n",res)

Output

Running the above code gives us the following result −

Given list is :
[78, 14, 0, 11]
list with relative ordering of elements :
[3, 2, 0, 1]

With enumerate and sorted

With enumerate and sorted function we retrieve each element and then create a dictionary container containing enumerate and sorted function. We get each element though this container using map function.

Example

 Live Demo

listA = [78, 14, 0, 11]
# printing original list
print("Given list is : \n",listA)
# using sorted() and enumerate
temp = {val: key for key, val in enumerate(sorted(listA))}
res = list(map(temp.get, listA))
# printing result
print("list with relative ordering of elements : \n",res)

Output

Running the above code gives us the following result −

Given list is :
[78, 14, 0, 11]
list with relative ordering of elements :
[3, 2, 0, 1]

Updated on: 04-Jun-2020

321 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements