When should I use list.count(0), and how do I to discount the "False" item?
<p><code>a.count(0)</code> always returns 11, so what should I do to discount the <code>False</code> and return 10?</p>

<pre><code>a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9]
</code></pre>

<p>Since <code>count</code> returns the number of items equal to its input, and since <code>0</code> is equal to <code>False</code> in Python, one way to approach this is to pass in something that is equal to <code>0</code> but is not equal to <code>False</code>.</p>

<p>Python itself provides no such object, but we can write one:</p>

<pre><code>class Zero:
    def __eq__(self, other):
        return other == 0 and other is not False

print([1, 2, 0, False].count(Zero()))
</code></pre>

<p>Be aware that there are other things in Python that, like <code>False</code>, are equal to <code>0</code>. I can think of <code>0.0</code>, <code>decimal.Decimal(0)</code>, and <code>fractions.Fraction(0,1)</code>. Furthermore, anybody can subclass <code>int</code> to create other "fake 0 values", just like <code>False</code>. The code above counts all of these, treating <code>False</code> as the only special case, but you might want to do something different in your <code>__eq__</code>.</p>

<p>Of course "under the covers" this is very similar to just doing <code>sum(other == 0 and other is not False for other in a)</code>. But considering how <code>count()</code> is defined, it should come as no surprise that <code>a.count(x)</code> is similar to <code>sum(x == y for y in a)</code>.</p>

<p>You would only do this in the rare case where you have for some reason already decided to use <code>count</code> (perhaps because you're using some third-party code that's going to call it), and need to come up with a suitable object to pass it. Basically, it treats <code>count</code> as a function that calls an arbitrary function we write (requiring only that this function be the <code>__eq__</code> function of the argument) and counts the number of true return values. This is an accurate description of what <code>count</code> does, but not really the point of <code>count</code> since <code>sum</code> is more explicit.</p>

python list count boolean