
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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]
Advertisements