Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Count positive and negative numbers in a list in Python program
In this article, we will learn how to count positive and negative numbers in a Python list using different approaches. We'll explore various methods from simple loops to more advanced functional programming techniques.
Problem statement ? We are given a list, we need to count positive and negative numbers in it and display them.
Using For Loop
The most straightforward approach is to iterate through each element and check if it's positive or negative using a for loop ?
numbers = [1, -2, -4, 6, 7, -23, 45, 0]
pos_count, neg_count = 0, 0
for num in numbers:
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)
Positive numbers in the list: 5 Negative numbers in the list: 3
Using While Loop
Alternatively, we can use a while loop with an index to iterate through the list ?
numbers = [1, -2, -4, 6, 7, -23, 45, 0]
pos_count, neg_count = 0, 0
index = 0
while index < len(numbers):
if numbers[index] >= 0:
pos_count += 1
else:
neg_count += 1
index += 1
print("Positive numbers in the list:", pos_count)
print("Negative numbers in the list:", neg_count)
Positive numbers in the list: 5 Negative numbers in the list: 3
Using Lambda Functions
We can use filter() with lambda expressions to separate positive and negative numbers, then count them ?
numbers = [1, -2, -4, 6, 7, -23, 45, 0]
pos_count = len(list(filter(lambda x: x >= 0, numbers)))
neg_count = len(list(filter(lambda x: x < 0, numbers)))
print("Positive numbers in the list:", pos_count)
print("Negative numbers in the list:", neg_count)
Positive numbers in the list: 5 Negative numbers in the list: 3
Using List Comprehension
List comprehension provides a concise way to count positive and negative numbers ?
numbers = [1, -2, -4, 6, 7, -23, 45, 0]
pos_count = len([x for x in numbers if x >= 0])
neg_count = len([x for x in numbers if x < 0])
print("Positive numbers in the list:", pos_count)
print("Negative numbers in the list:", neg_count)
Positive numbers in the list: 5 Negative numbers in the list: 3
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| For Loop | High | Good | Beginners, clear logic |
| While Loop | Medium | Good | When index is needed |
| Lambda | Medium | Fair | Functional programming |
| List Comprehension | High | Good | Concise, Pythonic code |
Conclusion
All methods effectively count positive and negative numbers in a list. The for loop approach is most readable for beginners, while list comprehension offers the most Pythonic solution. Choose based on your coding style and requirements.
