← Back to Python, page 2

python-0025 · Easy fresher

What values are falsy in Python, and why does 'if items:' work for empty lists?

False, None, zero of any numeric type, and empty containers or strings are falsy; everything else is truthy by default. if items: is the idiomatic emptiness check because an empty list is falsy. Classes control truthiness with __bool__ or, failing that, __len__.

Full answer
python
values = [0, 0.0, "", [], {}, set(), None, False, "0", [0], " ", 0.1]
print([v for v in values if not v])
print([v for v in values if v])

class Basket:
    def __init__(self, items): self.items = items
    def __len__(self): return len(self.items)
print(bool(Basket([])), bool(Basket(["pen"])))

count = 0
print(count or "no value", count if count is not None else "no value")

Output:

text
[0, 0.0, '', [], {}, set(), None, False]
['0', [0], ' ', 0.1]
False True
no value 0

The string '0', the list [0] and a space are truthy because they are non-empty, which trips up people coming from other languages. Basket has no __bool__, so Python uses __len__. The last line shows a classic bug: count or 'no value' replaces a legitimate 0 with the fallback, while an explicit is not None test keeps it. Use plain truthiness for 'is it empty', and explicit comparisons when zero or empty strings are valid values.

python
values = [0, 0.0, "", [], {}, set(), None, False, "0", [0], " ", 0.1]
print([v for v in values if not v])
print([v for v in values if v])

class Basket:
    def __init__(self, items): self.items = items
    def __len__(self): return len(self.items)
print(bool(Basket([])), bool(Basket(["pen"])))

count = 0
print(count or "no value", count if count is not None else "no value")

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Zero, empty containers, None and False are falsy
  • Non-empty strings like '0' are truthy
  • __bool__ or __len__ define truthiness
  • x or default replaces valid zeros

Common mistakes

  • Using or for defaults when 0 is valid
  • Writing if len(items) == 0

Follow-ups

  • How does numpy handle truthiness of arrays?
  • What does the walrus operator add to conditions?

Tips

  • List the falsy values