The bool() function in Python converts a value to a Boolean (True or False). It is a built-in function that returns False for falsy values like 0, None, empty sequences ([], '', {}), and False itself. All other values are truthy.
Basic Usage
print(bool(1)) # True
print(bool(0)) # False
print(bool('')) # False
print(bool('abc')) # True
Advanced: Custom Objects
You can define __bool__() or __len__() in your class to control Boolean conversion:
class MyClass:
def __bool__(self):
return True # Always truthy
If __bool__ is not defined, Python falls back to __len__(). If neither is defined, the object is always True.
Common Use Cases
- Filtering items from a list:
list(filter(bool, data)) - Conditional checks:
if bool(x):is equivalent toif x: - Validation: Checking if a user input is non-empty
Performance Note
bool() is efficient for explicit conversion, but implicit Boolean checks (e.g., if x:) are generally preferred for readability.
Understanding bool() helps you write cleaner, more predictable Python code.