Python Python bool(): Convert Values to Boolean — Syntax, Truthiness Rules, C…
page info
name Goposu datetime⏰ 25-10-11 01:40 hit👁️ 13 comment💬 0text

Python bool(): Convert a value to True or False
The built-in bool()
function converts a value to its boolean representation. In Python, “truthiness” is determined by type-specific rules: some values are considered falsy, while most others are truthy. Understanding these rules helps you write robust validation, control flow, and data-cleaning logic.
Syntax
bool(x)
Parameter: Any object (x
) implementing boolean semantics via __bool__()
or __len__()
.
Returns: True
or False
based on x
’s truthiness. If x
is omitted, bool()
returns False
only for bool()
on empty or falsy values; note that calling bool()
with no argument is invalid.
Truthiness rules
- Falsy:
False
,None
, numeric zero (0
,0.0
,0j
), empty containers ([]
,()
,{}
,set()
,""
,range(0)
), and objects whose__bool__()
returnsFalse
or__len__()
returns0
. - Truthy: All other values, including non-zero numbers, non-empty strings, and non-empty containers.
Quick examples
print(bool(1)) # True
print(bool(0)) # False
print(bool("hello")) # True
print(bool("")) # False
print(bool([1, 2])) # True
print(bool([])) # False
print(bool(None)) # False
print(bool(True)) # True
print(bool(False)) # False
Custom objects
Define truthiness by implementing __bool__()
. If absent, Python falls back to __len__()
and considers len(obj) == 0
as falsy.
class NonEmptyIfPositive:
def __init__(self, n):
self.n = n
def __bool__(self):
return self.n > 0
x = NonEmptyIfPositive(3)
y = NonEmptyIfPositive(0)
print(bool(x)) # True
print(bool(y)) # False
Common use cases
- Input validation: Check presence of values before processing.
- Control flow: Use truthy/falsy conditions in
if
statements. - Data cleaning: Filter out empty records or zero measurements.
records = ["a", "", "b"]
present = [r for r in records if bool(r)] # ["a", "b"]
Pitfalls and caveats
- Whitespace strings:
" "
(space) is non-empty and thus truthy; trim before checks if necessary. - NumPy arrays:
bool(np.array([1, 2]))
raisesValueError
due to ambiguous truth value; usearr.any()
orarr.all()
. - Custom types: Poorly defined
__bool__()
can mislead logic; keep semantics consistent and predictable. - Chained conditions: Remember that
and
/or
return operands, not strictly booleans; wrap withbool()
if you requireTrue
/False
.
# Whitespace is truthy
print(bool(" ")) # True
# and/or return operands
val = "" or "fallback"
print(val) # "fallback"
print(bool(val)) # True
Performance notes
- Built-in speed:
bool()
is implemented in C; conversions are fast. - Lazy evaluation in conditions: Prefer generator-based checks with
any()
/all()
to avoid building temporary lists. - Container checks: For lists, sets, dicts, use the container directly in boolean context (
if items:
)—it’s clear and efficient.
Comparison with any() and all()
- bool(x): Converts a single object to
True
/False
based on its truthiness. - any(iterable):
True
if at least one element is truthy; empty iterable yieldsFalse
. - all(iterable):
True
only if every element is truthy; empty iterable yieldsTrue
.
vals = [0, "", None, "x"]
print(bool(vals)) # True (non-empty list)
print(any(vals)) # True ("x" is truthy)
print(all(vals)) # False (0, "", None are falsy)
FAQ
- Is
bool
a type? - Yes.
bool
is a subclass ofint
with valuesTrue
andFalse
(which behave like1
and0
in arithmetic). - How do I check if a container is non-empty?
- Use it directly in a condition:
if items:
. This is equivalent toif bool(items):
and checkslen(items)
. - Why does
bool("False")
returnTrue
? - Because
"False"
is a non-empty string. Parse semantics explicitly if you need textual truth values.
Related keywords
Python bool, truthiness, falsy values, empty containers, __bool__, __len__, any vs all, boolean context, validation
comment list 0
There are no registered comments.