I have a list of Booleans:
[True, True, False, False, False, True]
and I am looking for a way to count the number of True
in the list (so in the example above, I want the return to be 3
.) I have found examples of looking for the number of occurrences of specific elements, but is there a more efficient way to do it since I'm working with Booleans? I'm thinking of something analogous to all
or any
.
True
is equal to1
.You can use
sum()
:If you are only concerned with the constant
True
, a simplesum
is fine. However, keep in mind that in Python other values evaluate asTrue
as well. A more robust solution would be to use thebool
builtin:UPDATE: Here's another similarly robust solution that has the advantage of being more transparent:
P.S. Python trivia:
True
could be true without being 1. Warning: do not try this at work!Much more evil:
Just for completeness' sake (
sum
is usually preferable), I wanted to mention that we can also usefilter
to get the truthy values. In the usual case,filter
accepts a function as the first argument, but if you pass itNone
, it will filter for all "truthy" values. This feature is somewhat surprising, but is well documented and works in both Python 2 and 3.The difference between the versions, is that in Python 2
filter
returns a list, so we can uselen
:But in Python 3,
filter
returns an iterator, so we can't uselen
, and if we want to avoid usingsum
(for any reason) we need to resort to converting the iterator to a list (which makes this much less pretty):After reading all the answers and comments on this question, I thought to do a small experiment.
I generated 50,000 random booleans and called
sum
andcount
on them.Here are my results:
Just to be sure, I repeated it several more times:
And as you can see,
count
is 3 times faster thansum
. So I would suggest to usecount
as I did incount_it
.Python version: 3.6.7
CPU cores: 4
RAM size: 16 GB
OS: Ubuntu 18.04.1 LTS
I prefer
len([b for b in boollist if b is True])
(or the generator-expression equivalent), as it's quite self-explanatory. Less 'magical' than the answer proposed by Ignacio Vazquez-Abrams.Alternatively, you can do this, which still assumes that bool is convertable to int, but makes no assumptions about the value of True:
ntrue = sum(boollist) / int(True)