Bird
Raised Fist0
Pythonprogramming~5 mins

Truthy and falsy values in Python - Time & Space Complexity

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Time Complexity: Truthy and falsy values in Python
O(1)
Understanding Time Complexity

We want to see how checking if a value is true or false in Python takes time as the input changes.

How does the time to decide truthiness grow when the input gets bigger or more complex?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def is_truthy(value):
    if value:
        return True
    else:
        return False

# Example usage
print(is_truthy([1, 2, 3]))
print(is_truthy([]))

This code checks if a given value is considered true or false in Python.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking the value's truthiness, which may involve looking at elements if the value is a collection.
  • How many times: Depends on the type; for example, an empty list is checked quickly, but a non-empty list does not require checking elements.
How Execution Grows With Input

When the input is simple like numbers or empty containers, the check is very fast and almost constant time.

Input Size (n)Approx. Operations
10 (small list)Checks if list is empty, usually 1 operation
100 (larger list)Still usually 1 operation to check if empty or not
1000 (large list)Still 1 operation for emptiness check; no need to check all elements

Pattern observation: The time to check truthiness does not grow with the size of the input for most built-in types.

Final Time Complexity

Time Complexity: O(1)

This means checking if a value is true or false happens in constant time, no matter how big the input is.

Common Mistake

[X] Wrong: "Checking if a list is true means looking at every item inside it."

[OK] Correct: Python only checks if the list is empty or not, which is a quick check, not a full scan.

Interview Connect

Understanding how Python quickly decides if something is true or false helps you write efficient code and answer questions about performance clearly.

Self-Check

"What if we changed the input to a custom object with a complex __bool__ method? How would the time complexity change?"

Practice

(1/5)
1. Which of the following values is considered falsy in Python?
easy
A. An empty list []
B. A non-empty string 'hello'
C. The integer 5
D. A non-empty dictionary {'key': 'value'}

Solution

  1. Step 1: Understand falsy values in Python

    Falsy values are those that behave like False in conditions. Common falsy values include None, 0, empty sequences like [], '', and empty collections like {}.
  2. Step 2: Check each option

    An empty list [] is an empty list, which is falsy. Options B, C, and D are non-empty and thus truthy.
  3. Final Answer:

    An empty list [] -> Option A
  4. Quick Check:

    Empty list is falsy = A [OK]
Hint: Empty containers and zero are falsy, others are truthy [OK]
Common Mistakes:
  • Thinking non-empty collections are falsy
  • Confusing zero with non-zero numbers
  • Assuming all strings are falsy
2. Which of the following is the correct way to check if a variable x is falsy in Python?
easy
A. if not x:
B. if x == False:
C. if x is False:
D. if x = False:

Solution

  1. Step 1: Understand Python falsy check syntax

    To check if a value is falsy, use if not x: which tests if x behaves like False in a boolean context.
  2. Step 2: Analyze each option

    if x == False: compares x to False but misses other falsy values like 0 or ''. if x is False: checks identity with False, which is too strict. if x = False: has a syntax error (= instead of ==). if not x: is the correct idiomatic way.
  3. Final Answer:

    if not x: -> Option A
  4. Quick Check:

    Use if not x: to check falsy [OK]
Hint: Use 'if not x:' to test falsy values in Python [OK]
Common Mistakes:
  • Using assignment '=' instead of comparison '=='
  • Checking identity with 'is False' instead of truthiness
  • Comparing directly to False misses other falsy values
3. What will be the output of the following code?
values = [0, 1, '', 'Python', [], [1, 2]]
result = [bool(v) for v in values]
print(result)
medium
A. [True, True, True, True, True, True]
B. [False, True, False, True, False, True]
C. [False, False, False, False, False, False]
D. [True, False, True, False, True, False]

Solution

  1. Step 1: Evaluate boolean value of each element

    0, empty string '', and empty list [] are falsy, so their bool() is False. Non-zero numbers, non-empty strings, and non-empty lists are truthy, so bool() is True.
  2. Step 2: Map each value to bool()

    values = [0(False), 1(True), ''(False), 'Python'(True), [] (False), [1, 2](True)]
  3. Final Answer:

    [False, True, False, True, False, True] -> Option B
  4. Quick Check:

    Falsy are 0, '', [] = False [OK]
Hint: Empty or zero values are False, others True in bool() [OK]
Common Mistakes:
  • Assuming all numbers are True
  • Thinking empty strings are True
  • Confusing empty and non-empty lists
4. The following code is intended to print "Falsy" if val is falsy, but it always prints "Truthy". What is the error?
val = 0
if val == False:
    print("Falsy")
else:
    print("Truthy")
medium
A. Using '==' instead of 'is' for comparison
B. The variable 'val' should be converted to bool first
C. Comparing with False misses some falsy values
D. No error; the code works correctly

Solution

  1. Step 1: Understand comparison with False

    Using val == False only matches if val equals exactly False or behaves equal to it. But some falsy values like 0 compare equal to False, so this seems correct here.
  2. Step 2: Check why it prints "Truthy"

    Actually, 0 == False is True, so it should print "Falsy". If it prints "Truthy", likely the code is different or the question expects the explanation that comparing with False is not reliable for all falsy values like empty containers or None.
  3. Final Answer:

    Comparing with False misses some falsy values -> Option C
  4. Quick Check:

    Use 'if not val:' to catch all falsy [OK]
Hint: Use 'if not val:' to catch all falsy values, not '== False' [OK]
Common Mistakes:
  • Thinking '==' always works for falsy check
  • Using 'is' instead of '==' incorrectly
  • Not realizing empty containers are falsy but not equal to False
5. You want to filter out all falsy values from a list data = [0, 1, '', 'text', [], [1], None]. Which code snippet correctly creates a new list with only truthy values?
hard
A. filtered = [x for x in data if x is not False]
B. filtered = [x for x in data if x == True]
C. filtered = [x for x in data if bool(x) == False]
D. filtered = [x for x in data if x]

Solution

  1. Step 1: Understand filtering truthy values

    To keep only truthy values, we filter with if x which keeps values that behave like True.
  2. Step 2: Analyze each option

    filtered = [x for x in data if x] uses if x, which is correct. filtered = [x for x in data if x == True] checks x == True, which excludes truthy but not exactly True values (like 1). filtered = [x for x in data if bool(x) == False] keeps falsy values (bool(x) == False). filtered = [x for x in data if x is not False] excludes only False but keeps other falsy values like 0 or ''.
  3. Final Answer:

    filtered = [x for x in data if x] -> Option D
  4. Quick Check:

    Use 'if x' to filter truthy values [OK]
Hint: Use list comprehension with 'if x' to keep truthy values [OK]
Common Mistakes:
  • Using '== True' excludes some truthy values
  • Filtering with 'bool(x) == False' keeps falsy values
  • Using 'is not False' misses other falsy values