Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Calculate the percentage of positive elements of the list
When calculating the percentage of positive elements in a list, we can use list comprehension along with the len() method to count positive values and compute the percentage.
Example
Here's how to calculate the percentage of positive elements in a list ?
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 : 60.0
How It Works
A list containing positive, negative, and zero values is defined
List comprehension
[element for element in my_list if element > 0]filters only positive elementsThe length of positive elements is divided by the total length and multiplied by 100 to get percentage
In this example, 6 out of 10 elements are positive, giving us 60.0%
Alternative Method Using sum()
You can also use sum() with a generator expression for a more memory-efficient approach ?
my_list = [14, 62, -22, 13, -87, 0, -21, 81, 29, 31]
positive_percentage = (sum(1 for element in my_list if element > 0) / len(my_list)) * 100
print("The list is :")
print(my_list)
print("Percentage of positive elements:", positive_percentage)
The list is : [14, 62, -22, 13, -87, 0, -21, 81, 29, 31] Percentage of positive elements: 60.0
Conclusion
Use list comprehension with len() to calculate percentage of positive elements. The sum() method with generator expression is more memory-efficient for large lists.
