0
0
Pythonprogramming~5 mins

Boolean values (True and False) in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Boolean values (True and False)
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the list gets bigger, the time to count True values grows in a simple way.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The number of steps grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to count True values grows in a straight line as the list gets longer.

Common Mistake

[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.

Interview Connect

Understanding how simple checks grow with input size helps you explain your code clearly and think about efficiency in real tasks.

Self-Check

"What if we stopped counting as soon as we found the first True? How would the time complexity change?"