[1, 1, 1, 2, 2, 3].count(True)
>>> 3
Why does this return 3
instead of 6
, if bool(i)
returns True
for all values i
not equal to 0
?
In [33]: True == 1
Out[33]: True
In [34]: True == 2
Out[34]: False
In [35]: True == 3
Out[35]: False
True
and False
are instances of bool
, and bool
is a subclass of int
.
From the docs:
[Booleans] represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of plain integers, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.
This is better done with a comprehension:
>>> sum(1 for i in [1,1,1,2,2,3,0] if i)
6
or
sum(bool(i) for i in [1,1,1,2,2,3,0])
Or count the opposite way, since there is no ambiguity about False is something other than 0
>>> li=[1, 1, 1, 2, 2, 3, 0]
>>> len(li) - li.count(False)
6
Better still:
sum(map(bool,li))
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