Counting the number of True Booleans in a Python List
list
has a count
method:
>>> [True,True,False].count(True)
2
This is actually more efficient than sum
, as well as being more explicit about the intent, so there's no reason to use sum
:
In [1]: import random
In [2]: x = [random.choice([True, False]) for i in range(100)]
In [3]: %timeit x.count(True)
970 ns ± 41.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [4]: %timeit sum(x)
1.72 µs ± 161 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
True
is equal to 1
.
>>> sum([True, True, False, False, False, True])
3