Example :
Input: list1 = [2, -7, 5, -64, -14] Output: pos = 2, neg = 3 Input: list2 = [-12, 14, 95, 3] Output: pos = 3, neg = 1
Example # 1: Counting positive and negative numbers from a given list using a for loop
Iterate through each item in the list using a for loop and check if num & gt ; = 0, a condition for testing positive numbers. If the condition is met, then increase the pos_count, otherwise, increase the neg_count.
# Python program for counting positive and negative numbers in a list # list of numbers list1 = [ 10 , - 21 , 4 , - 45 , 66 , - 93 , 1 ] pos_count, neg_count = 0 , 0 # iterate over each number in the list for num in list1: # check status if num" = 0 : pos_count + = 1 else : neg_count + = 1 print ( "Positive numbers in the list:" , pos_count) print ( "Negative numbers in the list:" , neg_count) |
Exit :
Positive numbers in the list: 4 Negative numbers in the list: 3
Example # 2. Using a while loop
< p> # Python program for counting positive and negative numbers in a list # list of numbers list1 = [ - 10 , - 21 , - 4 , - 45 , - 66 , 93 , 11 ] pos_count, neg_count = 0 , 0 num = 0 # using a while loop while (num & lt; len (list1)): # check status if list1 [num]" = 0 : pos_count + = 1 else : neg_count + = 1 # n increment number num + = 1 print ( "Positive numbers in the list:" , pos_count) print ( "Negative numbers in the list:" , neg_count) |
Exit:
Positive numbers in the list: 2 Negative numbers in the list: 5
Example # 3: Using Python lambda expressions
# Python program for counting positives # and negative numbers in the list # list of numbers list1 = [ 10 , - 21 , - 4 , 45 , 66 , 93 , - 11 ] neg_count = len < / code> ( list ( filter ( lambda x: (x & lt; 0 ), list1))) # we can also do len (list1) - neg_count pos_count = len ( list ( filter ( lambda x: (x" = 0 ), list1))) print ( " Positive numbers in the list: " , pos_count) print ( "Negative numbers in the list: " , neg_count) |
Output:
Positive numbers in the list: 4 Negative numbers in the list: 3
Example # 4: Usage # Python program for counting positives # and negative numbers in the list # list of numbers list1 = [ - 10 , - 21 , - 4 , - 45 , - 66 , - 93 , 11 ] only_pos = [num for num in list1 if num" = 1 ] pos_count = len (only_pos) print ( "Positive numbers in the list: " , pos_count) print ( "Negative numbers in the list:" , len (list1) - pos_count) |
Exit:
Positive numbers in the list: 1 Negative numbers in the list: 6