Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer to boolean conversion in count() method

Tags:

python

[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?

like image 808
FreeAsInGimme Avatar asked Oct 07 '12 00:10

FreeAsInGimme


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 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.

like image 166
unutbu Avatar answered Sep 29 '22 01:09

unutbu


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))
like image 38
the wolf Avatar answered Sep 29 '22 03:09

the wolf