5 Best Ways to Count Positive and Negative Numbers in a Python List

πŸ’‘ Problem Formulation: You have a list of integers in Python, and you want to count how many are positive and how many are negative. Given a list such as [12, -7, 5, -3, 9, -1], you wish to obtain an output similar to {'Positive': 3, 'Negative': 3}. This article discusses five distinct methods to solve this problem efficiently.

Method 1: Using a Simple For Loop

This method involves iterating through the list using a for loop and incrementally counting the positive and negative numbers separately. It’s straightforward and does not require importing any external libraries, making it highly accessible for beginners.

Here’s an example:

numbers = [12, -7, 5, -3, 9, -1]
positive_count, negative_count = 0, 0
for num in numbers:
    if num > 0:
        positive_count += 1
    elif num < 0:
        negative_count += 1
print({'Positive': positive_count, 'Negative': negative_count})

Output: {'Positive': 3, 'Negative': 3}

This snippet defines a list of numbers and initializes two counters for positive and negative numbers. As it loops through the numbers, it checks if each one is positive or negative and updates the counts accordingly. This method is very clear and easy to understand.

Method 2: Using the filter() Function

The filter() function in Python can be used to iterate over each element in the list and return those that meet a specific condition. We can use this function to segregate positive and negative numbers and then count them separately.

Here’s an example:

numbers = [12, -7, 5, -3, 9, -1]
positive_count = len(list(filter(lambda x: x > 0, numbers)))
negative_count = len(list(filter(lambda x: x < 0, numbers)))
print({'Positive': positive_count, 'Negative': negative_count})

Output: {'Positive': 3, 'Negative': 3}

This code utilizes two calls to filter() with lambda functions to extract positive and negative numbers, then converts the filters to lists and takes their length to get the count of each.

Method 3: Using List Comprehensions

Python’s list comprehensions offer a concise way to create lists. They can be used to count positive and negative numbers by generating sublists of positive and negative numbers and then taking the length of these sublists.

Here’s an example:

numbers = [12, -7, 5, -3, 9, -1]
positive_count = len([num for num in numbers if num > 0])
negative_count = len([num for num in numbers if num < 0])
print({'Positive': positive_count, 'Negative': negative_count})

Output: {'Positive': 3, 'Negative': 3}

The code creates two separate lists using list comprehensions: one for positive numbers and the other for negative numbers. It then calculates their length to obtain the counts.

Method 4: Using collections.Counter

The collections module provides the Counter class to count hashable objects. It can be used to count positive and negatives by iterating through the list and counting occurrences of the categories ‘Positive’ and ‘Negative’ based on the conditions.

Here’s an example:

from collections import Counter
numbers = [12, -7, 5, -3, 9, -1]
count = Counter('Positive' if num > 0 else 'Negative' for num in numbers)
print(count)

Output: Counter({'Positive': 3, 'Negative': 3})

This snippet imports the Counter from collections and creates a Counter object by iterating over the numbers and categorizing each as ‘Positive’ or ‘Negative’.

Bonus One-Liner Method 5: Using a Dictionary Comprehension

A dictionary comprehension in Python is similar to a list comprehension but produces a dictionary. We can use this feature to create a dictionary that contains the count of positive and negative numbers in a single line of code.

Here’s an example:

numbers = [12, -7, 5, -3, 9, -1]
count = {'Positive': sum(1 for num in numbers if num > 0), 'Negative': sum(1 for num in numbers if num < 0)}
print(count)

Output: {'Positive': 3, 'Negative': 3}

This one-liner utilizes dictionary comprehension along with the sum() function to count positive and negative numbers. By summing over a generator expression, it tallies how many times each condition is met.

Summary/Discussion

  • Method 1: Simple For Loop. Strengths: Readable, easy to understand. Weaknesses: Verbosity, not the most Pythonic way.
  • Method 2: Using filter() Function. Strengths: Functional programming style, concise. Weaknesses: Requires conversion to list, may not be immediately clear to beginners.
  • Method 3: Using List Comprehensions. Strengths: Pythonic, concise. Weaknesses: Creates unnecessary lists, which might be memory consuming for very large lists.
  • Method 4: Using collections.Counter. Strengths: Efficient for large data sets, elegant. Weaknesses: Requires knowledge of collections module.
  • Bonus Method 5: Dictionary Comprehension. Strengths: Very concise, Pythonic. Weaknesses: Slightly obscure for someone not familiar with dictionary comprehensions.