Skip to main content
The bool type in Python is a built-in data type representing one of two possible truth values: True or False. It is a direct subclass of the integer class (int), meaning boolean values behave as integers in numeric contexts, where True evaluates to 1 and False evaluates to 0. Because True and False are implemented as singletons in Python, they have fixed memory addresses throughout the lifecycle of a program.

Truth Value Testing

Any object in Python can be evaluated in a boolean context (such as an if or while condition) or converted explicitly using the bool() constructor. Under the hood, the bool() constructor calls the object’s __bool__() dunder method. If __bool__() is not defined, Python falls back to the __len__() method. If neither is defined, the object evaluates to True by default. An object evaluates to False (often referred to as “falsy”) if it is:
  1. A constant defined to be false: None or False.
  2. A zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1).
  3. An empty sequence or collection: '' (empty string), (), [], {}, set(), range(0).

Logical Operators

Python provides three logical operators to perform boolean arithmetic: not, and, and or. Unlike the not operator, which strictly returns a bool object, the and and or operators utilize short-circuit evaluation and return the actual object evaluated, which may not be of type bool.
  • not x: Returns True if x is falsy; returns False if x is truthy.
  • x and y: Evaluates x. If x is falsy, it returns x (short-circuiting). Otherwise, it evaluates and returns y.
  • x or y: Evaluates x. If x is truthy, it returns x (short-circuiting). Otherwise, it evaluates and returns y.

Bitwise Operators on Booleans

Because bool is a subclass of int, bitwise operators (&, |, ^, ~) can be applied to boolean values. The bitwise AND (&), OR (|), and XOR (^) operators return a bool type when both operands are booleans, evaluating both operands and bypassing the short-circuiting behavior of and and or. However, the bitwise NOT operator (~) returns an int because it operates directly on the underlying integer representation of the boolean (1 for True, 0 for False).
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More