Editor

Python Program to Count Positive and Negative Numbers in a List

Beginner · Lists

A positive number is greater than 0 and a negative number is less than 0, while 0 itself is neither. This program goes through a list and counts how many numbers fall into each of the three groups.

Program

count_positive_negative.py
numbers = [12, -7, 0, 45, -3, 8, 0, -19, 6] # or: numbers = [int(x) for x in input("Enter numbers: ").split()]
positive = 0
negative = 0
zero = 0
for num in numbers:
if num > 0:
positive += 1
elif num < 0:
negative += 1
else:
zero += 1 # neither positive nor negative
print("List:", numbers)
print("Positive numbers:", positive)
print("Negative numbers:", negative)
print("Zeros:", zero)
Output
List: [12, -7, 0, 45, -3, 8, 0, -19, 6]
Positive numbers: 4
Negative numbers: 3
Zeros: 2

How it works

  1. Three counters start at 0, one for each group.
  2. if num > 0 catches the positive numbers and elif num < 0 the negative ones.
  3. A number that is neither greater nor less than 0 must be 0, so the else branch counts the zeros.
  4. The three counts always add up to the length of the list, 9 here.

Other ways to write it

Collecting the numbers in lists

Collecting the numbers in lists
numbers = [12, -7, 0, 45, -3, 8, 0, -19, 6]
positives = [n for n in numbers if n > 0]
negatives = [n for n in numbers if n < 0]
print(f"Positive ({len(positives)}):", positives)
print(f"Negative ({len(negatives)}):", negatives)
Output
Positive (4): [12, 45, 8, 6]
Negative (3): [-7, -3, -19]

List comprehensions keep the numbers themselves, so you can print them as well as count them.

Counting with sum()

Counting with sum()
numbers = [12, -7, 0, 45, -3, 8, 0, -19, 6]
print("Positive numbers:", sum(n > 0 for n in numbers))
print("Negative numbers:", sum(n < 0 for n in numbers))
Output
Positive numbers: 4
Negative numbers: 3

Each comparison gives True or False, and Python treats True as 1 and False as 0, so adding them up counts the numbers that pass.

Try it yourself

Add a sum of the positive numbers and a sum of the negative numbers to the program.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises