Comparison operators in Python - Time & Space Complexity
We want to understand how fast comparison operators run when used in code.
Specifically, we ask: how does the time to compare values change as inputs grow?
Analyze the time complexity of the following code snippet.
values = [5, 3, 8, 6]
threshold = 4
count = 0
for v in values:
if v > threshold:
count += 1
print(count)
This code counts how many numbers in a list are greater than a threshold.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparison using > operator inside a loop.
- How many times: Once for each item in the list.
Each new item adds one more comparison operation.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 comparisons |
| 100 | 100 comparisons |
| 1000 | 1000 comparisons |
Pattern observation: The number of comparisons grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the list gets bigger.
[X] Wrong: "Comparison operators take constant time no matter what, so time complexity is always O(1)."
[OK] Correct: While one comparison is quick, doing many comparisons in a loop adds up, so total time depends on how many comparisons happen.
Understanding how comparisons add up helps you explain how your code handles bigger inputs clearly and confidently.
"What if we replaced the list with a nested list and compared items inside inner lists? How would the time complexity change?"