Python – Find the frequency of numbers greater than each element in a list

When it is required to find the frequency of numbers greater than each element in a list, a list comprehension and the 'sum' method can be used to count elements efficiently.

Example

The following example demonstrates how to count elements greater than each position in the list ?

my_list = [24, 13, 72, 22, 12, 47]

print("The list is :")
print(my_list)

my_result = [sum(1 for element in my_list if element > index) for index in my_list]

print("The result is :")
print(my_result)

Output

The list is :
[24, 13, 72, 22, 12, 47]
The result is :
[3, 5, 1, 4, 5, 2]

How It Works

The list comprehension works by taking each element as a reference point and counting how many elements in the entire list are greater than it. For example:

  • For element 24: elements greater are [72, 47, 47] = 3 count

  • For element 13: elements greater are [24, 72, 22, 47] = 4 count

  • For element 72: no elements greater = 0 count

  • For element 22: elements greater are [24, 72, 47] = 3 count

Alternative Using Nested Loop

Here's a more explicit approach using nested loops for better understanding ?

my_list = [24, 13, 72, 22, 12, 47]
result = []

for current_element in my_list:
    count = 0
    for element in my_list:
        if element > current_element:
            count += 1
    result.append(count)

print("The list is :", my_list)
print("The result is :", result)
The list is : [24, 13, 72, 22, 12, 47]
The result is : [3, 5, 1, 4, 5, 2]

Conclusion

Use list comprehension with `sum()` for a concise solution to count elements greater than each position. The nested loop approach offers better readability for understanding the logic.

Updated on: 2026-03-26T00:58:08+05:30

286 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements