Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Core language & syntaxJuniorVery commonTheory

How does Python decide whether an arbitrary object is truthy or falsy in a boolean context?

Answer

Python calls `__bool__` on the object if it is defined; if not, it falls back to `__len__` and treats a zero length as falsy; if neither is defined, the object is truthy by default. Built-in falsy values include `None`, `False`, `0`, `0.0`, empty strings, and empty containers such as `[]`, `{}`, `()` and `set()`. This is why `if my_list:` is idiomatic for an emptiness check instead of `if len(my_list) > 0:` or `if my_list == []:`.

Strong answer includes

  • __bool__ then __len__ fallback
  • built-in falsy values
  • idiomatic emptiness checks

Practical example

A custom `Queue` class that defines `__len__` will be falsy when empty, so

Python example
if not queue:

correctly detects an empty queue without needing a dedicated

Python example
is_empty()

method.

#truthiness#dunder-methods

Sources

Data modelPython Software Foundation · Dunder methods, object identity, attribute lookup and the descriptor and context manager protocolsThe Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semantics