Count positive and negative numbers in a list in Python program

PythonServer Side ProgrammingProgramming

In this article, we will learn about the solution to the problem statement given below.

Problem statement − We are given a list iterable, we need to count positive and negative numbers in it and display them.

Approach 1: Brute-force approach using iteration construct(for)

Here we need to iterate each element in the list using a for loop and check whether num>=0, to filter the positive numbers. If the condition evaluates to be true, then increase pos_count otherwise, increase neg_count.

Example

 Live Demo

list1 = [1,-2,-4,6,7,-23,45,-0]
pos_count, neg_count = 0, 0
# enhanced for loop  
for num in list1:
   # check for being positive
   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)

Output

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

Approach 2: Brute-force approach using iteration construct(while)

Here we need to iterate each element in the list using a for loop and check whether num>= 0, to filter the positive numbers. If the condition evaluates to be true, then increase pos_count otherwise, increase neg_count.

Example

 Live Demo

list1 = [1,-2,-4,6,7,-23,45,-0]
pos_count, neg_count = 0, 0
num = 0
# while loop
while(num < len(list1)):
   # check
   if list1[num] >= 0:
      pos_count += 1
   else:
      neg_count += 1
   # increment num
   num += 1
print("Positive numbers in the list: ", pos_count)
print("Negative numbers in the list: ", neg_count)

Output

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

Approach 3: Using Python Lambda Expressions

Here we take the help of filter and lambda expressions we can directly differentiate between positive and negative numbers.

Example

 Live Demo

list1 = [1,-2,-4,6,7,-23,45,-0]
neg_count = len(list(filter(lambda x: (x < 0), list1)))
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: 5
Negative numbers in the list: 3

All the variables are declared in the local scope and their references are seen in the figure above.

Conclusion

In this article, we have learned how to count positive and negative numbers in a list.

raja
Published on 23-Dec-2019 12:18:37
Advertisements