Skip to content

Truthiness and short-circuit evaluation [ref]

Problem

  • Evaluate the truth values of [], [0], "", 0, None, and 3.
  • Select the first truthy value among None, [], and "ready".
  • Evaluate False and 1 / 0 without division.
  • Safely check whether the first item of items = [] is positive.
  • Label items = [] as "empty" with a conditional expression.
  • Test whether any value of [0, 0, 3] and all values of [1, 2, 3] are truthy.

Python solution

[bool(x) for x in ([], [0], "", 0, None, 3)]
# [False, True, False, False, False, True]

None or [] or "ready"  # 'ready'

False and 1 / 0  # False

items = []
bool(items and items[0] > 0)  # False

"empty" if not items else "nonempty"  # 'empty'

any([0, 0, 3])  # True
all([1, 2, 3])  # True