Is it guaranteed that False == 0
and True == 1
, in Python (assuming that they are not reassigned by the user)? For instance, is it in any way guaranteed that the following code will always produce the same results, whatever the version of Python (both existing and, likely, future ones)?
0 == False # True
1 == True # True
['zero', 'one'][False] # is 'zero'
Any reference to the official documentation would be much appreciated!
As noted in many answers, bool
inherits from int
. The question can therefore be recast as: "Does the documentation officially say that programmers can rely on booleans inheriting from integers, with the values 0
and 1
?". This question is relevant for writing robust code that won't fail because of implementation details!
sum(bool_list)
. Otherwise, you'd have to writesum(1 for x bool_list if x)
. – Faginbool_list.count(True)
is more explicit; it's also about 3 times faster… :) – Gelasius