Logical operators in conditions in Python - Time & Space Complexity
Logical operators in conditions help decide which code runs based on true or false checks.
We want to see how these checks affect the time it takes for the program to run as input changes.
Analyze the time complexity of the following code snippet.
def check_values(nums, threshold):
count = 0
for num in nums:
if num > threshold and num % 2 == 0:
count += 1
return count
This code counts how many numbers in a list are greater than a threshold and even.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list.
- How many times: Once for every number in the input list.
As the list gets bigger, the program checks each number once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of checks grows directly with the list size.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the list gets bigger.
[X] Wrong: "Logical operators make the code run slower by multiplying the time."
[OK] Correct: The checks happen together for each item, so they add a small fixed cost, not extra loops.
Understanding how conditions affect time helps you explain your code clearly and shows you know what happens as data grows.
"What if we changed the condition to use 'or' instead of 'and'? How would the time complexity change?"