Computer >> Computer tutorials >  >> Programming >> Python

Python program to count positive and negative numbers in a list


In this article, we will learn about the solution and approach to solve the given problem statement.

Problem statement

Given a list iterable we need to count all the positive and negative numbers available in the iterable.

Her we will be discussing two approaches −

  • Brute-force approach
  • Using lambda inline function

Approach 1 − Brute-force method

Example

 

list1 = [1,-9,15,-16,13]
pos_count, neg_count = 0, 0
for num in list1:
   if num >= 0:
      pos_count += 1
   else:
      neg_count += 1
print("Positive numbers : ", pos_count)
print("Negative numbers : ", neg_count)

Output

Positive numbers : 3
Negative numbers : 2

Approach 2 − Using lambda & filter functions

Example

list1 = [1,-9,15,-16,13]
neg_count = len(list(filter(lambda x: (x < 0), list1)))
pos_count = len(list(filter(lambda x: (x >= 0), list1)))
print("Positive numbers : ", pos_count)
print("Negative numbers : ", neg_count)

Output

Positive numbers : 3
Negative numbers : 2

Conclusion

In this article, we learned about the approach to count positive & negative numbers in a list.