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 finding the rank (position) each element would have if the list were sorted in ascending order.

Using sorted() and index()

We first sort the entire list and then find the index of each element in the sorted list ?

Example

numbers = [78, 14, 0, 11]

# printing original list
print("Given list is:")
print(numbers)

# using sorted() and index()
result = [sorted(numbers).index(i) for i in numbers]

# printing result
print("List with relative ordering of elements:")
print(result)

The output of the above code is ?

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

Using enumerate() and sorted()

With enumerate() and sorted() function we create a dictionary that maps each value to its rank, then use map() to get the relative order ?

Example

numbers = [78, 14, 0, 11]

# printing original list
print("Given list is:")
print(numbers)

# using sorted() and enumerate
rank_map = {val: rank for rank, val in enumerate(sorted(numbers))}
result = list(map(rank_map.get, numbers))

# printing result
print("List with relative ordering of elements:")
print(result)

The output of the above code is ?

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

How It Works

In both methods, we determine the rank of each element:

  • 0 is the smallest element, so it gets rank 0
  • 11 is the second smallest, so it gets rank 1
  • 14 is the third smallest, so it gets rank 2
  • 78 is the largest element, so it gets rank 3

Comparison

Method Time Complexity Best For
sorted() + index() O(n²) Simple implementation
enumerate() + sorted() O(n log n) Better performance

Conclusion

Use the enumerate() method for better performance with larger lists. The index() method is simpler but less efficient for large datasets.

Updated on: 2026-03-15T18:04:48+05:30

558 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements