pythonbooleanlist-comprehensionnonetype

How to count the number of occurrences of `None` in a list?


I'm trying to count things that are not None, but I want False and numeric zeros to be accepted too. Reversed logic: I want to count everything except what it's been explicitly declared as None.

Example

Just the 5th element it's not included in the count:

>>> list = ['hey', 'what', 0, False, None, 14]
>>> print(magic_count(list))
5

I know this isn't Python normal behavior, but how can I override Python's behavior?

What I've tried

So far I founded people suggesting that a if a is not None else "too bad", but it does not work.

I've also tried isinstance, but with no luck.


Solution

  • Just use sum checking if each object is not None which will be True or False so 1 or 0.

    lst = ['hey','what',0,False,None,14]
    print(sum(x is not None for x in lst))
    

    Or using filter with python2:

    print(len(filter(lambda x: x is not None, lst))) # py3 -> tuple(filter(lambda x: x is not None, lst))
    

    With python3 there is None.__ne__() which will only ignore None's and filter without the need for a lambda.

    sum(1 for _ in filter(None.__ne__, lst))
    

    The advantage of sum is it lazily evaluates an element at a time instead of creating a full list of values.

    On a side note avoid using list as a variable name as it shadows the python list.