Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 381
Hrabal Avatar asked Apr 02 '15 21:04

Hrabal


People also ask

How do you count the number of occurrences of an element in a list?

Using the count() Function The "standard" way (no external libraries) to get the count of word occurrences in a list is by using the list object's count() function. The count() method is a built-in function that takes an element as its only argument and returns the number of times that element appears in the list.

How do you count null values in a list?

Using “count” function: There is an inbuilt function in Python “count( )” that returns the number of occurrences of an element inside a Python list. Syntax:name_of_list. count(object), where “object” is the element whose count from the list is to be returned.

How do you count the number of occurrences of a number in a list in Python?

Operator. countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. It returns the Count of a number of occurrences of value.


1 Answers

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.

like image 143
Padraic Cunningham Avatar answered Oct 13 '22 08:10

Padraic Cunningham