Boolean integer in count () method

[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 ​​of i not equal to 0 ?

+7
source share
2 answers
 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 true values ​​of False and True. Two objects representing the values ​​False and True are the only Boolean objects. The Boolean type is a subtype of prime integers, and Boolean values ​​behave like the values ​​0 and 1, respectively, in almost all contexts , the exception is that when converting to a string, the string "False" or "True" is returned, respectively.

+3
source

This is best done with the understanding:

 >>> 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 consider the way back, as there is no ambiguity regarding False - this is something other than 0

 >>> li=[1, 1, 1, 2, 2, 3, 0] >>> len(li) - li.count(False) 6 

Even better:

 sum(map(bool,li)) 
+2
source

All Articles