PythonPython Variables and Data TypesPython data types

What is a Boolean data type?

Question 35 of 88 · Updated

On this page

A Boolean is a value of Python's built-in bool type that represents one of two logical states: True or False. Boolean values are commonly used to represent conditions, comparison results, feature flags and decisions about whether a program should perform an action.

The bool type has exactly two instances, True and False. Both are immutable. Python also allows many non-Boolean objects to be evaluated in a Boolean context using its truth-value testing protocol.

1. Creating Boolean values#

Use the case-sensitive literals True and False, or call the built-in bool constructor.

PYTHON
print(type(True).__name__, type(False).__name__) print(bool(), bool(1), bool(0))

Output:

bool bool
False True False

The constructor bool() without an argument returns False. With an argument, bool evaluates the object's truth value and returns the corresponding Boolean singleton.

Do not write lowercase true or false as Python Boolean literals. Those spellings are ordinary identifiers, unless defined elsewhere. JSON uses lowercase true and false, but Python source uses True and False.

2. Truthy and falsy values#

A value need not have type bool to be tested in a condition. An object that evaluates to True in a Boolean context is called truthy; one that evaluates to False is called falsy.

Value or categoryTruth value
FalseFalse
NoneFalse
Numeric zero: 0, 0.0, 0jFalse
Empty string or bytesFalse
Empty list, tuple, dict, set or rangeFalse
TrueTrue
Nonzero ordinary numberTrue
Nonempty ordinary string or containerTrue
Custom objectDetermined by its truth-value protocol
PYTHON
print(bool(-1), bool(0.0), bool(0j), bool(None)) print(bool([]), bool({}), bool(""), bool("False"))

Output:

True False False False
False False False True

A negative number is nonzero, so -1 is truthy. The string "False" is nonempty, so it is truthy despite the meaning of the text.

Nonempty containers are normally truthy regardless of the truth values of their elements: a list containing one False value is still a nonempty list.

3. Comparisons and conditions#

Ordinary comparisons between built-in integers produce Boolean results.

PYTHON
print(5 > 3, 5 == 3, 5 != 3) print(not [], not "hello")

Output:

True False True
True False

Comparison results can drive if statements, loops and conditional expressions. The not operator always returns a Boolean result after testing its operand's truth value.

Custom types can implement rich comparison methods that return non-Boolean objects. In a Boolean context those results are subsequently truth-tested. Some numerical array types intentionally reject ambiguous truth testing.

4. Why bool is a subclass of int#

Python's bool type inherits from int. True behaves numerically like 1 and False like 0 in many arithmetic and equality operations.

PYTHON
print(True + True, int(False), isinstance(True, int)) print(len({True, 1, 1.0}))

Output:

2 0 True
1

True, 1 and 1.0 compare equal and have compatible hashes, so the set contains one distinct element. This can also matter when mixing Boolean and numeric dictionary keys.

Although Boolean values can participate in arithmetic, prefer explicit logical meaning when representing a condition. In a validated API that accepts integer quantities but not Boolean flags, remember that isinstance(value, int) alone also accepts bool. An exact-type check or a separate exclusion of bool may be necessary, depending on the API contract.

The fact that bool inherits from int does not mean every integer is a Boolean object. The integer 2 is truthy, but its type is int.

5. Logical operators and short-circuit evaluation#

Python provides and, or and not.

xyx and yx or y
FalseFalseFalseFalse
FalseTrueFalseTrue
TrueFalseFalseTrue
TrueTrueTrueTrue

This truth table assumes actual bool operands. With arbitrary objects, and and or return one of their operands rather than necessarily returning True or False.

  • x and y returns x if x is falsy; otherwise it evaluates and returns y.
  • x or y returns x if x is truthy; otherwise it evaluates and returns y.
  • not x returns the negation of x's truth value as a bool.
PYTHON
print(repr([] or "fallback"), repr("ready" and 42)) print(False and (1 / 0), True or (1 / 0))

Output:

'fallback' 42
False True

Neither division by zero is executed. The left operand determines whether evaluation of the right operand is necessary. This is called short-circuit evaluation. It is useful for conditional checks but also means that side effects in the right operand may not occur.

The logical operators are introduced here because they operate on truth values. Detailed operator precedence and short-circuit evaluation are separate curriculum topics.

6. How Python determines an object's truth value#

Python's data model defines the truth-value testing protocol. When a condition or bool call tests an object, the object's type can customize the result.

Loading diagram…

This diagram shows the normal protocol and the specific invalid return-type case for __bool__. Exceptions raised by either method propagate, and invalid lengths also raise errors. Special methods are resolved according to Python's special-method lookup rules, not simply by looking for attributes on individual instances.

An object is considered truthy by default if its type defines neither __bool__ nor __len__. When __bool__ is present, it takes precedence over __len__.

Example: truthiness based on container length#

PYTHON
class Basket: def __init__(self, items): self.items = items def __len__(self): return len(self.items) print(bool(Basket([])), bool(Basket([1])))

Output:

False True

The Basket class defines a length but no explicit Boolean method. An empty basket is therefore falsy and a nonempty basket is truthy.

Example: explicit Boolean behavior#

PYTHON
class Switch: def __bool__(self): return False def __len__(self): return 3 print(bool(Switch()))

Output:

False

Despite its positive length, Switch evaluates to False because __bool__ takes precedence.

The __bool__ method must return an actual bool, not an arbitrary truthy object or the integer 1. The __len__ method must return a valid nonnegative integer length within implementation constraints.

Two independently tested error cases are:

PYTHON
class InvalidBoolean: def __bool__(self): return 1 # bool(InvalidBoolean()) raises TypeError. class InvalidLength: def __len__(self): return -1 # bool(InvalidLength()) raises ValueError.

Keep truth-value methods inexpensive and predictable where practical. A custom implementation can perform arbitrary computations, raise exceptions or have side effects; a Boolean check is not automatically a constant-time operation.

7. Checking many values with any and all#

The built-in functions any and all test truth values across an iterable.

PYTHON
print(any([0, "", 7]), all([1, "yes", 3])) print(any([]), all([]))

Output:

True True
False True

any returns True as soon as it encounters a truthy element; all returns False as soon as it encounters a falsy element. Both return actual Boolean values. For an empty iterable, any returns False and all returns True, consistent with existential and universal quantification.

For n elements, the worst-case number of truth tests is O(n). These functions use constant auxiliary state apart from the iterable and the work done by individual truth tests. Generator expressions can avoid materializing an intermediate list when that is appropriate.

8. Practical example: parsing a Boolean flag from text#

Environment variables, form inputs and configuration files often supply strings instead of Boolean values. Calling bool directly is usually not a valid text parser: bool("false") returns True.

Define the accepted vocabulary and reject unknown values explicitly.

PYTHON
def parse_flag(text): normalized = text.strip().lower() if normalized in {"true", "1", "yes"}: return True if normalized in {"false", "0", "no"}: return False raise ValueError("Invalid Boolean value") print(parse_flag(" YES "), parse_flag("false")) try: parse_flag("maybe") except ValueError: print("Invalid flag")

Output:

True False
Invalid flag

This parser intentionally accepts only the six specified strings after whitespace trimming and lowercasing. It assumes that the supplied value is a string. A production boundary should validate the input type, decide how missing values are treated and follow the configuration format's contract.

For a flag of length m, normalization takes O(m) time and can require O(m) additional string storage. The accepted vocabulary has a fixed number of short strings.

Never use eval to parse Boolean input from an untrusted source.

9. False, None and zero are not interchangeable#

Several different values are falsy, but they do not necessarily represent the same application state.

PYTHON
def choose_limit(limit): return 10 if limit is None else limit print(choose_limit(None), choose_limit(0))

Output:

10 0

If None represents an omitted limit and zero is an explicit valid limit, the distinction matters. Writing limit or 10 would replace both None and zero with 10. A truth-value check alone cannot distinguish absence from valid falsy values.

Use is None when absence is the specific condition. Use ordinary truth testing when the intended condition is emptiness, zero or falsehood according to the object's type.

10. Practical example: a Boolean decision#

PYTHON
def can_submit(active, remaining): return active and remaining > 0 print(can_submit(True, 2), can_submit(True, 0), can_submit(False, 2))

Output:

True False False

The function assumes active is an actual bool and remaining is a valid integer. Under those assumptions the result is a bool. If active can instead be an arbitrary falsy object, the and expression could return that object directly. Validate the input contract or deliberately normalize the result when a strict Boolean return is required.

This example illustrates a local business rule, not complete access control. Security-sensitive operations must enforce permissions and relevant state on the trusted server side, rather than relying on a client-side Boolean flag.

11. Common mistakes and best practices#

MistakeCorrect approach
bool("False") to parse configurationUse an explicit accepted string vocabulary
Assuming and and or always return boolRemember that they can return operands
Confusing a missing value with zeroUse an explicit None check when appropriate
Assuming a list containing False is falsyOrdinary list truthiness depends on length
Using isinstance(value, int) to exclude Boolean flagsCheck the intended type contract explicitly
Returning 1 from __bool__Return True or False
Using bitwise operators for short-circuit logicUse and, or and not for ordinary logical conditions

Prefer a direct condition such as if enabled when enabled is a Boolean flag. An explicit identity or type check can be appropriate when the exact Boolean singleton or strict input type is part of the contract.

Frequently asked questions#

What are the possible values of bool?#

True and False are the two instances of bool.

Is bool("0") False?#

No. "0" is a nonempty string, so it is truthy.

Is False the same as None?#

No. False is a bool object; None is the singleton instance of NoneType. Both are falsy but represent different values.

What is the difference between bool(x) and not x?#

bool(x) returns the truth value of x as True or False. not x returns its logical negation.

Does bool inherit from int?#

Yes. This explains numeric behavior such as int(True) being 1 and isinstance(True, int) returning True.

Can custom objects define their truth value?#

Yes. A type can define __bool__ or provide a valid __len__ method. The Boolean method takes precedence.

Interview-ready answer#

A Boolean is Python's built-in bool data type with exactly two values, True and False. It represents logical conditions and is commonly produced by comparisons. Python supports truth-value testing for other objects: zero, None and empty ordinary containers are falsy, while many other values are truthy. Custom classes can define __bool__ or __len__ to control truth testing. The bool type inherits from int, and logical and/or can return operands rather than actual Boolean values; not always returns a bool. For reliable code, distinguish missing values from valid falsy values and parse textual flags explicitly.

Official references#

Verification note: Eleven output-based examples and two independent expected-exception tests were executed on CPython 3.13.5 and passed. The Mermaid flowchart was manually reviewed for syntax, labels and the truth-value protocol; a local Mermaid CLI was not found, so parser-level and public-site rendering checks were not performed. Official references are supplied under the authorised offline research exception and were not checked live.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design