Topic 32 of 64
Boolean
Overview
Python's bool is a subclass of int (True == 1, False == 0). Understanding truthiness (truthy/falsy) is crucial for writing idiomatic Python conditionals and avoiding common bugs.
Syntax
python
# Boolean literals
x = True
y = False
# Falsy values in Python
bool(0) # False
bool("") # False
bool([]) # False
bool(None) # False
bool({}) # False
# Truthy values
bool(1) # True
bool("hello") # True
bool([0]) # True (non-empty list)Common Pitfalls
- True + True == 2 in Python because bool is a subclass of int — avoid arithmetic with booleans.
- Use 'is True' vs '== True' carefully — 'if value:' is idiomatic; 'if value == True:' may give unexpected results for non-bool truthy objects.
- Interview tip: None, 0, empty collections, and empty strings are all falsy — useful for default/guard patterns.
Real-World Example
Using truthiness to guard against empty inputs
example
python
def process(data: list) -> str:
if not data: # same as: if len(data) == 0
return "No data provided"
return f"Processing {len(data)} items"
print(process([])) # "No data provided"
print(process([1, 2, 3])) # "Processing 3 items"