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

PythonServer Side ProgrammingProgramming

When it is required to find the frequency of numbers greater than each element in a list, a list comprehension and the ‘sum’ method is used.

Below is a demonstration of the same −

Example

 Live Demo

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 index <= element) 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, 6, 2]

Explanation

  • A list of integers is defined and is displayed on the console.

  • A list comprehension is used to iterate over the elements of the list, and check if the index of every element is less than the element itself.

  • If so, it is added using the ‘sum’ method, converted to a list, and assigned to a variable.

  • This is displayed as output on the console.

raja
Published on 04-Sep-2021 11:23:31
Advertisements