python program to count positive and negative numbers from list

In this example, you will find and count positive/negative numbers from list.

Example 1: Using Loop

    
# Python program to count positive and negative number using loop

list1 = [-1,12,31,-4,-56,36,71,-28,9]
  
positive_count, negative_count = 0, 0
num = 0
  
# using while loop
while(num < len(list1)):
    if list1[num] >  0:
        positive_count += 1
    else:
        negative_count += 1

    num += 1
    
print("Positive numbers in the list: ", positive_count)
print("Negative numbers in the list: ", negative_count)
       

Output :

    
Positive numbers in the list:  5
Negative numbers in the list:  4
    

Explanation :

The logic of the program is simple, we iterate through each element of the list and check its number is greater then zero or not. If the number is greater then 0 then it is positive number so we increment positive counter, else update negative counter.

Example 2: Using Lambda

    
# Python program to count positive and negative number using lambda function
list1 = [-1,12,31,-4,-56,36,71,-28,9]

positive_count = len(list(filter(lambda x: (x >= 0), list1)))
negative_count = len(list(filter(lambda x: (x < 0), list1)))
  
print("Positive numbers in the list: ", positive_count)
print("Negative numbers in the list: ", negative_count)
       

Output :

    
Even numbers in the list:  4
Odd numbers in the list:  5
    

Explanation :

Lambda functions are anonymous functions which are kind of instant run functions. Here, we create two separate list for positive and negative numbers using filter function and then count the length of each.


Share your thoughts

Ask anything about this examples