Python program to count positive and negative numbers in a list
Last Updated :
19 Dec, 2024
Improve
In this article, we will explore various methods to count positive and negative numbers in a list. The simplest way to do this is by using a loop. This method counts the positive and negative numbers in a list by iterating through each element using for loop.
a = [10, -20, 30, -40, 50, -60, 0]
# Counts the positive numbers
pos = 0
# Counts the negative numbers
neg = 0
# Iterate through the list
for n in a:
if n > 0:
pos += 1
elif n < 0:
neg += 1
print(pos)
print(neg)
Output
3 3
Let’s explore other different method:
Table of Content
Using filter() Function
filter() function can be used to filter positive and negative numbers and we can count them using len(). It is better than a manual loop since it avoids the explicit creation of new lists during iteration.
a = [10, -20, 30, -40, 50, -60, 0]
# Count positive numbers using filter
pos = len(list(filter(lambda x: x > 0, a)))
# Count negative numbers using filter
neg = len(list(filter(lambda x: x < 0, a)))
print(pos)
print(neg)
Output
3 3
Using List Comprehension
List comprehension provides a more concise way to count positive and negative numbers. It iterate through the list and create new lists based on conditions.
a = [10, -20, 30, -40, 50, -60, 0]
# Count positive numbers
pos = len([n for n in a if n > 0])
# Count negative numbers
neg = len([n for n in a if n < 0])
print(pos)
print(neg)
Output
3 3