How to count the number of occurrences of `None` in a list?
Two ways:
One, with a list expression
len([x for x in lst if x is not None])
Two, count the Nones and subtract them from the length:
len(lst) - lst.count(None)
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
.