Skip to content

S2Q1 · Count Positive Integers Ignoring None

⚡ Quick Reference

Function: count_positive_ignore_none(nums: list) -> int

Core idea: count elements that are not None and greater than zero.

def count_positive_ignore_none(nums: list) -> int:
    return sum(1 for x in nums if x is not None and x > 0)

Key rules: - None is skipped - use x is not None - 0 is not positive - use x > 0 (strict) - Negative numbers are also skipped


Problem Statement

Problem

Write a function count_positive_ignore_none(nums) that counts positive integers in a list, ignoring None values and zero.

Example:

Input
[1, -2, 3, 0, None, 4]
Output
3

Positives: 1, 3, 4 → count = 3


Why x is not None instead of x != None?

None should always be compared with is / is not, not == / !=. Using x > 0 directly on None would raise a TypeError in Python 3 - so the None check must come first with short-circuit and.

Short-circuit evaluation saves the day

x is not None and x > 0 - if x is None, the first condition is False and Python never evaluates x > 0. Without the None guard first, None > 0 raises TypeError.


Solution approaches

def count_positive_ignore_none(nums: list) -> int:
    return sum(1 for x in nums if x is not None and x > 0)
def count_positive_ignore_none(nums: list) -> int:
    count = 0
    for x in nums:
        if x is None:
            continue
        if x > 0:
            count += 1
    return count
def count_positive_ignore_none(nums: list) -> int:
    return len(list(filter(lambda x: x is not None and x > 0, nums)))

filter(lambda x: ..., nums) keeps only positive non-None values. len(list(...)) counts them.

def count_positive_ignore_none(nums: list) -> int:
    return len([x for x in nums if x is not None and x > 0])

Key takeaways

01

x is not None - always use identity for None

Use is and is not to check for None, never == or !=. None is a singleton - identity comparison is both correct and more Pythonic.

02

None check must come before comparison

Always guard against None before comparing with >, <, etc. - comparing None to a number raises TypeError in Python 3. Short-circuit and ensures the guard runs first.

03

x > 0 excludes both zero and negatives

Strict greater-than automatically excludes zero and all negative numbers - no need for a separate x != 0 check.