Easy: Warm-Ups · Problem 3 of 82

Truthy or Falsy

EasyPython BasicsPython

Python decides whether a value counts as true or false, for example in an if statement. Write count_truthy(values) that returns how many items in the list are truthy: how many make bool(item) equal to True.

Understand the problem

Predict what Python does. Do not run it; reason from the rules.

What is bool("0")?

  1. False, because the text is zero
  2. True, because the string is not empty

A string is falsy only when it is empty. "0" has one character, so it is truthy. Python does not read the text inside the string.

Which of these is falsy?

  1. [0]
  2. " "
  3. 0.0
  4. "False"

0.0 (zero of any number type) is falsy. [0] is a list with one item, " " is a string with one space and "False" is a string with five letters: all non-empty, so all truthy.

How many of these are truthy? [0, "0", [], [0], None, " "]

Falsy: 0, [] and None. Truthy: "0", [0] and " ". So 3.

Write the solution

Return a count. The tests use many different kinds of values.

def count_truthy(values):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

Do you need to compare each item with anything, or can Python answer the question directly?

Hint 2: the shape of the answer

An item is truthy if if item: would run. Count the items for which that is true. sum() over a generator of 1s works well.

Reflect

Solution

def count_truthy(values):
    return sum(1 for value in values if value)

Another way: bool as a number

def count_truthy(values):
    return sum(map(bool, values))

What this tests: the truthiness rules, and a generator expression with sum.

The rules to remember. Falsy values are: None, False, zero of any numeric type (0, 0.0), and empty containers and strings ("", [], (), {}, set()). Almost everything else is truthy, including "0", "False", [0], float("nan") and any object of your own class (unless it defines __bool__ or __len__).

Style: write if items: rather than if len(items) > 0:, and if value is None: when you mean exactly None (an empty list is not None).

Cost: O(n).

What an interviewer might ask next: What is the difference between if x: and if x is not None:? Give an input where they behave differently. (An empty list, or 0.)