Python – Calculate the percentage of positive elements of the list

PythonServer Side ProgrammingProgramming

When it is required to calculate the percentage of positive elements of the list, a list comprehension and the ‘len’ method are used.

Below is a demonstration of the same −

Example

 Live Demo

my_list = [14, 62, -22, 13, -87, 0, -21, 81, 29, 31]

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

my_result = (len([element for element in my_list if element > 0]) / len(my_list)) * 100

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

Output

The list is :
[14, 62, -22, 13, -87, 0, -21, 81, 29, 31]
The result is :
0

Explanation

  • A list is defined and displayed on the console.

  • A list comprehension is used to iterate over the list, and check if an element is greater than 0, and these elements are divided by product of length of list and 100.

  • The length of the above operation is assigned to a variable.

  • This is the output that is displayed on the console.

raja
Published on 06-Sep-2021 08:48:25
Advertisements