Glossary

Truthiness

Truthiness (or truth value testing) is Python's convention that any object can be evaluated in a boolean context (in if, while, and, or, not expressions). An object is falsy if it is None, False, zero in any numeric type (0, 0.0, 0j, Decimal(0), Fraction(0)), or an empty collection ('', [], (), {}, set(), frozenset(), range(0)). Everything else is truthy.

Custom classes can define their truthiness by implementing __bool__() (which should return True or False) or __len__() (an object with length zero is falsy). If neither is defined, instances are truthy by default. __bool__ takes precedence over __len__ when both are defined.

Truthiness enables concise Python idioms: if items: (check for non-empty collection), name = user_name or "Anonymous" (default value via or), debug and print("message") (conditional execution via and). The and and or operators short-circuit and return the determining operand (not necessarily True or False): [] or "default" returns "default", and [1, 2] and "yes" returns "yes". Understanding truthiness is essential for writing clean, Pythonic conditional logic.

Related terms: Boolean, None, Conditional Statement

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.