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:
[1, -2, 3, 0, None, 4]
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¶
Key takeaways¶
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.
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.
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.