Back to Blog
Python

Python Truthy and Falsy Values Explained

python truthy falsy: Learn how Python evaluates objects as true or false, the complete list of falsy values, and how to use truthiness effectively in conditionals.

Pythontruthyfalsyboolean contexttype coercionconditional logic
Diagram showing Python truthy and falsy values with examples of objects evaluated in boolean context.

The Boolean Context in Python

In Python, every object can be evaluated in a boolean context, meaning it is treated as either True or False when used in an if statement, while loop, or with boolean operators like and, or, and not. This behavior is commonly referred to as python truthy falsy. The built-in bool() function converts any object to its boolean equivalent, which is useful for understanding how Python evaluates a value.

print(bool(0)) # False print(bool(1)) # True print(bool([])) # False print(bool([1, 2])) # True

The rules are simple: most objects are True by default, but a specific set of values are considered False. Knowing these rules helps you write concise and idiomatic conditionals.

The Complete List of Falsy Values

Python defines a small set of built-in values that are always False in a boolean context. These are:

ValueExample
Nonebool(None) is False
Falsebool(False) is False
Zero numeric values0, 0.0, 0j, Decimal(0), Fraction(0, 1)
Empty sequences'', (), [], b''
Empty mappings{}
Objects with __bool__ returning FalseCustom classes can define this
Objects with __len__ returning 0If __bool__ is not defined, Python falls back to __len__

Everything else is True. This includes non-empty strings, lists, tuples, dictionaries, sets, and any non-zero number.

falsy_values = [None, False, 0, 0.0, '', [], (), {}] for value in falsy_values: print(f"{value!r} -> {bool(value)}")

How Python Decides Truthiness for Custom Objects

For user-defined classes, Python checks for a __bool__ method first. If it exists, the method's return value is used directly. If __bool__ is not defined, Python looks for __len__. If __len__ is defined and returns 0, the object is False; otherwise it is True. If neither method is defined, the object is always True.

class Account: def __init__(self, balance): self.balance = balance def __bool__(self): return self.balance > 0 account = Account(0) print(bool(account)) # False account.balance = 100 print(bool(account)) # True

Implementing __bool__ gives you precise control over how instances behave in conditionals. This is particularly useful for domain objects where emptiness or validity is not simply about being None.

Using Truthiness in Conditionals and Loops

The most common use of truthiness is in if statements. Instead of comparing to an empty list or zero explicitly, you can rely on the object's truth value:

items = [] if items: print("Items exist") else: print("No items")

This is more readable than if len(items) > 0. The same applies to while loops and boolean expressions:

while queue: # process until queue is empty item = queue.pop() process(item)

Using truthiness also works with and and or. For example, a or b returns a if a is truthy, otherwise b. This is a common pattern for providing default values:

name = user_input or "default"

Here, if user_input is an empty string (falsy), the default is used. This is concise and idiomatic, but be careful: it also treats 0, None, and empty containers as falsy, which may not always be the intent.

Common Pitfalls and How to Avoid Them

A frequent mistake is confusing None with other falsy values. For example, if a function returns 0 or an empty list as a valid result, using if result: will treat it as missing. In such cases, you should check for None explicitly:

def find_user(id): # returns None if not found, otherwise a User object ... user = find_user(42) if user is not None: # process user

Another pitfall is relying on truthiness for numeric values. If 0 is a meaningful input, if value: will skip it. Instead, use if value is not None: or compare to 0 directly.

When working with pandas or numpy, truthiness of arrays can raise errors because arrays have ambiguous truth values. This is a separate topic, but it's worth remembering that the standard Python rules do not apply to every library.

When to Override Truthiness in Your Classes

You should override __bool__ when an object's boolean meaning is not obvious from its default state. For example, a Transaction might be considered True only if it has been approved. A Configuration object might be False if it is missing required settings.

class Configuration: def __init__(self, settings): self.settings = settings def __bool__(self): return bool(self.settings.get("enabled", False)) config = Configuration({}) print(bool(config)) # False

Overriding __len__ is useful for collection-like classes. If your class wraps a list or dict, you can delegate to the underlying container:

class Stack: def __init__(self): self._items = [] def __len__(self): return len(self._items) stack = Stack() print(bool(stack)) # False

This makes the class behave naturally with if stack:.

Performance and Readability Tradeoffs

Using truthiness is almost always faster than an explicit length check because it avoids a method call and a comparison. However, the performance difference is negligible in most applications. The real benefit is readability: if items: clearly communicates that you care about whether the collection has any elements.

That said, there are cases where explicit checks are better. If you need to distinguish between None and an empty list, truthiness cannot help. If you are working with a custom object whose __bool__ has side effects (which it shouldn't, but it could), you might prefer a direct attribute check.

The key is to choose the approach that best expresses the intent of your code. Truthiness is a powerful tool, but it is not a substitute for precise checks when the distinction matters.

python truthy falsy: Practical Usage and Code Examples | RYUSLOG DEV