Python Booleans
In Python, every value evaluates to either True or False when converted to a boolean or used in a conditional context (like an if statement or while loop). Understanding this mechanism—known as truthiness and falsiness—allows you to write concise and idiomatic Python code.
The bool Data Type
Python provides two built-in boolean constants: True and False. They belong to the bool class, which is a subclass of int (True has an integer value of 1, and False has a value of 0).
is_active = True
is_admin = False
print(type(is_active)) # Output: bool
print(True + True) # Output: 2
Explicit Conversion with bool()
You can check the truth value of any object by passing it to the built-in bool() function.
print(bool(10)) # Output: True
print(bool(0)) # Output: False
print(bool("hello")) # Output: True
print(bool("")) # Output: False
Truthy vs. Falsy Values
Instead of explicitly checking if a collection is empty or a number is zero (e.g., if len(my_list) > 0:), Python lets you evaluate objects directly.
Falsy Values in Python
An object is considered falsy if it evaluates to False in a boolean context. Python defines only a specific set of built-in falsy values:
| Category | Falsy Values |
|---|---|
| Constants | None, False |
| Numeric Zeros | 0, 0.0, 0j, Decimal(0), Fraction(0, 1) |
| Empty Sequences | "" (string), () (tuple), [] (list), bytes() |
| Empty Collections | {} (dict), set(), frozenset() |
| Custom Objects | Instances of classes that define __len__() returning 0 or __bool__() returning False |
Truthy Values
Everything else in Python is considered truthy. If an object is not in the falsy list above, bool(obj) returns True.
- Non-zero numbers:
1,-5,3.14 - Non-empty strings:
" ","False","0"(Note:" "with a space is non-empty, so it is truthy!) - Non-empty sequences/collections:
[0],(None,),{"a": 1}
Idiomatic Usage (Pythonic Code)
Leveraging truthy and falsy values yields cleaner code without redundant checks.
Example 1: Checking for Empty Collections
items = []
# Avoid (Unpythonic):
if len(items) == 0:
print("List is empty")
# Preferred (Pythonic):
if not items:
print("List is empty")
Example 2: Handling Default Values
name = input("Enter your name: ")
# If user hits Enter without typing, `name` is "" (falsy)
username = name or "Anonymous"
print(f"Welcome, {username}!")
Short-Circuit Evaluation (and / or)
Boolean operators in Python (and, or) do not always return True or False. Instead, they return the actual value of the last evaluated expression using short-circuit logic:
or: Returns the first truthy operand it encounters. If all are falsy, it returns the last operand.and: Returns the first falsy operand it encounters. If all are truthy, it returns the last operand.
# 'or' examples
result1 = "" or "Default" # Output: "Default" (1st falsy, returns 2nd)
result2 = "Alice" or "Bob" # Output: "Alice" (1st truthy, short-circuits)
# 'and' examples
result3 = "Python" and 42 # Output: 42 (Both truthy, returns last)
result4 = [] and "Data" # Output: [] (1st falsy, short-circuits)
Custom Objects & Boolean Behavior
You can define how instances of your custom classes evaluate to True or False by implementing the __bool__() or __len__() magic methods.
class ShoppingCart:
def __init__(self, items):
self.items = items
def __bool__(self):
# Cart is truthy only if it contains items
return len(self.items) > 0
empty_cart = ShoppingCart([])
full_cart = ShoppingCart(["Apple", "Milk"])
print(bool(empty_cart)) # Output: False
print(bool(full_cart)) # Output: True
if not empty_cart:
print("Your cart is empty!")
Order of Precedence: Python first looks for
__bool__(). If__bool__()is not defined, it checks__len__()(returningFalseif length is0). If neither is defined, all instances of the class evaluate toTrue.