Truthy and falsy values in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
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?
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 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.
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.
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.
[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.
Understanding how Python quickly decides if something is true or false helps you write efficient code and answer questions about performance clearly.
"What if we changed the input to a custom object with a complex __bool__ method? How would the time complexity change?"
Practice
falsy in Python?Solution
Step 1: Understand falsy values in Python
Falsy values are those that behave likeFalsein conditions. Common falsy values includeNone,0, empty sequences like[],'', and empty collections like{}.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.Final Answer:
An empty list[]-> Option AQuick Check:
Empty list is falsy = A [OK]
- Thinking non-empty collections are falsy
- Confusing zero with non-zero numbers
- Assuming all strings are falsy
x is falsy in Python?Solution
Step 1: Understand Python falsy check syntax
To check if a value is falsy, useif not x:which tests ifxbehaves likeFalsein a boolean context.Step 2: Analyze each option
if x == False: comparesxtoFalsebut misses other falsy values like0or''. if x is False: checks identity withFalse, which is too strict. if x = False: has a syntax error (=instead of==). if not x: is the correct idiomatic way.Final Answer:
if not x: -> Option AQuick Check:
Useif not x:to check falsy [OK]
- Using assignment '=' instead of comparison '=='
- Checking identity with 'is False' instead of truthiness
- Comparing directly to False misses other falsy values
values = [0, 1, '', 'Python', [], [1, 2]] result = [bool(v) for v in values] print(result)
Solution
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.Step 2: Map each value to bool()
values = [0(False), 1(True), ''(False), 'Python'(True), [] (False), [1, 2](True)]Final Answer:
[False, True, False, True, False, True] -> Option BQuick Check:
Falsy are 0, '', [] = False [OK]
- Assuming all numbers are True
- Thinking empty strings are True
- Confusing empty and non-empty lists
val is falsy, but it always prints "Truthy". What is the error?val = 0
if val == False:
print("Falsy")
else:
print("Truthy")Solution
Step 1: Understand comparison with False
Usingval == Falseonly matches ifvalequals exactlyFalseor behaves equal to it. But some falsy values like0compare equal to False, so this seems correct here.Step 2: Check why it prints "Truthy"
Actually,0 == Falseis 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.Final Answer:
Comparing with False misses some falsy values -> Option CQuick Check:
Use 'if not val:' to catch all falsy [OK]
- Thinking '==' always works for falsy check
- Using 'is' instead of '==' incorrectly
- Not realizing empty containers are falsy but not equal to False
data = [0, 1, '', 'text', [], [1], None]. Which code snippet correctly creates a new list with only truthy values?Solution
Step 1: Understand filtering truthy values
To keep only truthy values, we filter withif xwhich keeps values that behave like True.Step 2: Analyze each option
filtered = [x for x in data if x] usesif x, which is correct. filtered = [x for x in data if x == True] checksx == 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 onlyFalsebut keeps other falsy values like 0 or ''.Final Answer:
filtered = [x for x in data if x] -> Option DQuick Check:
Use 'if x' to filter truthy values [OK]
- Using '== True' excludes some truthy values
- Filtering with 'bool(x) == False' keeps falsy values
- Using 'is not False' misses other falsy values
