Core Concepts
Python's boolean values exhibit some surprising and unintuitive behaviors, including equality comparisons with integers and the ability to add True values together.
Abstract
The author recently learned two interesting quirks about Python boolean values:
Equality Comparison with Integers:
The boolean values True and False are equal to the integer values 1 and 0 respectively when using the == operator.
However, when using the is operator, True is not the same object as 1, and False is not the same as 0.
This distinction is due to the difference between checking for value equality (==) and object identity (is).
Adding True Values:
Since True is equal to 1, the author discovered that you can add True values together like integers.
This can be useful for quickly counting the number of True values in a list, as demonstrated by the example:ls = [True, True, False, True, False, False, True, False]
print(sum(ls)) # Output: 4
The author finds these behaviors both strange and entertaining, and suggests readers check out their Substack post for more cool Python boolean-related insights.
Stats
True == 1
False == 0
True + True == 2
True + True + True == 3
True + True + True + True == 4
Quotes
"Very strange and interesting. But it kinda does make sense I guess?"
"Unintuitive and strange behaviour, but entertaining in some way."