Boolean values (True and False) in Python - Time & Space Complexity
When working with Boolean values like True and False, it's helpful to see how quickly operations run as input changes.
We want to know how the time to check or use these values grows when we have more data.
Analyze the time complexity of the following code snippet.
values = [True, False, True, False, True]
count_true = 0
for val in values:
if val is True:
count_true += 1
print(count_true)
This code counts how many True values are in a list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list.
- How many times: Once for every item in the list.
As the list gets bigger, the time to count True values grows in a simple way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of steps grows directly with the number of items.
Time Complexity: O(n)
This means the time to count True values grows in a straight line as the list gets longer.
[X] Wrong: "Checking for True values takes the same time no matter how many items there are."
[OK] Correct: Each item must be checked one by one, so more items mean more time.
Understanding how simple checks grow with input size helps you explain your code clearly and think about efficiency in real tasks.
"What if we stopped counting as soon as we found the first True? How would the time complexity change?"