

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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]
- Related Questions & Answers
- Print the last occurrence of elements in array in relative order in C Program.
- Finding frequency in list of tuples in Python
- Program to find squared elements list in sorted order in Python
- Sort list elements in descending order in C#
- List frequency of elements in Python
- Finding sort order of string in JavaScript
- Finding reflection of a point relative to another point in JavaScript
- Program to get indices of a list after deleting elements in ascending order in Python
- How to change the order of elements in a list in R?
- Positive elements at even and negative at odd positions (Relative order not maintained) in C++
- Python Program to extracts elements from a list with digits in increasing order
- Delete List Elements in Python
- Finding squares in sorted order in JavaScript
- Assign range of elements to List in Python
- Python – Fractional Frequency of elements in List
Advertisements