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.
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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With