Advertisement
❮ Previous: Python Numbers & Math Module Next: Python Operators ❯

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

Try this code ❯


Advertisement

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

Try this code ❯


Advertisement

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.


Advertisement

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")

Try this code ❯

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}!")

Try this code ❯


Advertisement

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' 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)

Try this code ❯


Advertisement

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!")

Try this code ❯

Order of Precedence: Python first looks for __bool__(). If __bool__() is not defined, it checks __len__() (returning False if length is 0). If neither is defined, all instances of the class evaluate to True.

❮ Previous: Python Numbers & Math Module Next: Python Operators ❯
Advertisement