What are truthy and falsy values in Python?
Every object has a truth value when used in an if or while. Falsy values are False, None, zero of any numeric type, and empty containers such as '', [], (), {}, set() and range(0). Everything else is truthy unless its class defines __bool__ or __len__ to say otherwise.
Explain it simply
Think of a lunch box check before college. You do not ask "is the lunch box equal to full?"; you just ask "is there something in it?". Python does the same: an empty list, an empty string or the number zero counts as "nothing there" (falsy), and anything with content counts as "something" (truthy).
Example
for value in [0, 0.0, "", [], {}, None, "0", [0], " ", -1]:
print(repr(value), bool(value))
# 0 False
# 0.0 False
# '' False
# [] False
# {} False
# None False
# '0' True (a non-empty string)
# [0] True (a list with one item)
# ' ' True (a space is still a character)
# -1 True (any non-zero number)Idiomatic checks use this directly:
cart = []
if not cart:
print("Your cart is empty")For your own classes, Python first calls __bool__; if that is missing it calls __len__ and treats 0 as falsy; if both are missing the object is truthy.
What to say in the interview
"Python treats None, False, numeric zeros and empty collections as falsy and everything else as truthy. That is why if not items: is the idiomatic empty check. For custom classes, truthiness comes from __bool__, then __len__."
Common mistakes
- Writing
if x:whenxmay legitimately be0. If you mean "is it missing", writeif x is None:. - Assuming the string
"False"is falsy. It is a non-empty string, so it is truthy.