Open In App

Calculate the Percentage of Positive Elements of the List - Python

Last Updated : 30 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a list that contains positive and negative elements we need to calculate percentage of only positive elements of list. For example, we are having a list a = [10, -5, 3, 0, -8, 4] we only need to calculate positive element so that the output should be 50.0.

Using a loop

To calculate the percentage of positive elements in a list we can iterate through the list count positive elements and then divide by total number of elements multiplying by 100 to get percentage.

Python
a = [10, -5, 3, 0, -8, 4]  
p = 0 
for num in a:  
    if num > 0:  
        p += 1  

# Calculate the percentage of positive numbers  
per = (p / len(a)) * 100  

print(per)  

Output
50.0

Explanation:

  • Loop iterates through the list a and for each positive number (greater than 0) counter p is incremented.
  • After the loop percentage of positive numbers is calculated by dividing the count of positive numbers (p) by the total length of the list then multiplying by 100 to get the percentage which is then printed.

Using list comprehension

Using list comprehension we can create a new list containing only positive numbers from a with [num for num in a if num > 0]. The percentage of positive numbers is then calculated by dividing the length of this list by the length of a and multiplying by 100.

Python
a = [10, -5, 3, 0, -8, 4] 

# Use list comprehension to filter positive numbers, then calculate the percentage
p = (len([num for num in a if num > 0]) / len(a)) * 100  
print(p)  

Output
50.0

Explanation:

  • List comprehension [num for num in a if num > 0] creates a new list of positive numbers from the list a. The len() function is then used to count the number of positive numbers.
  • Percentage of positive numbers is calculated by dividing the count of positive numbers by the total length of the list a and multiplying by 100 to get the percentage which is then printed.

Using filter()

We can use the filter() function to extract positive numbers from the list a with filter(lambda x: x > 0, a). The percentage of positive numbers is then calculated by dividing the length of the filtered result by the length of a and multiplying by 100.

Python
a = [10, -5, 3, 0, -8, 4] 

# Use filter() to extract positive numbers, then calculate the percentage
p = (len(list(filter(lambda x: x > 0, a))) / len(a)) * 100  

print(p)  

Output
50.0

Explanation:

  • filter() function with lambda x: x > 0 filters out the positive numbers from the list a, and list() is used to convert the result into a list.
  • Percentage of positive numbers is calculated by dividing the length of filtered list by the length of original list a then multiplying by 100 to get the percentage which is printed.

Next Article
Practice Tags :

Similar Reads