0
0
Pythonprogramming~5 mins

Comparison operators in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Comparison operators
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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

Each new item adds one more comparison operation.

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

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

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the list gets bigger.

Common Mistake

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

Interview Connect

Understanding how comparisons add up helps you explain how your code handles bigger inputs clearly and confidently.

Self-Check

"What if we replaced the list with a nested list and compared items inside inner lists? How would the time complexity change?"