Skip to the solution
EasyDSA9 min read

What values are falsy in Python?

258 views

The problem

Question presented to candidate: "When you write if something: in Python, which values count as false? And how does Python decide that for an object of your own class?"

What a strong answer should cover:

  • The built-in falsy set: None, False, numeric zero of any type (0, 0.0, -0.0, 0j, Decimal(0), Fraction(0)), and empty containers ("", b"", (), [], {}, set(), frozenset(), range(0), bytearray()); everything else is truthy.
  • The protocol: bool(x) calls __bool__ if defined (it must return a real bool), otherwise __len__ (falsy when it is 0), otherwise the object is truthy.
  • Truthy surprises: "0", "False", " ", [0], [[]] and float("nan") are all truthy.
  • and / or short-circuit and return one of their operands, not True/False, which powers x or default.
  • The classic bug: if not x: treats a legitimate 0 or "" as missing; use if x is None: when absence and emptiness differ.

Code / implementation expected: Optional β€” a quick bool() table or a small class with __bool__ / __len__.

  • truthiness

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonThe falsy family, truthy look-alikes, and and/or return values
PythonThe __bool__ / __len__ protocol and the 0-vs-None bug

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 30 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

What are list/dict/set comprehensions?

Continue