0
0
Pythonprogramming~5 mins

Ternary conditional expression in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Ternary conditional expression
O(1)
Understanding Time Complexity

Let's see how the time it takes to run a ternary conditional expression changes as the input grows.

We want to know how the number of steps changes when we use this quick if-else shortcut.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def check_number(num):
    return "Positive" if num > 0 else "Non-positive"

result = check_number(10)
print(result)

This code checks if a number is positive or not using a ternary conditional expression.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A single comparison and return statement.
  • How many times: Exactly once per function call.
How Execution Grows With Input

Since the ternary expression runs just one check, the steps stay the same no matter the input size.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The work does not increase as input grows; it stays constant.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the ternary expression stays the same no matter how big the input is.

Common Mistake

[X] Wrong: "The ternary expression takes longer if the number is bigger because it compares the value."

[OK] Correct: The comparison is a single step and does not depend on the size of the number, so the time stays constant.

Interview Connect

Understanding that simple expressions like ternary conditionals run in constant time helps you explain your code clearly and shows you know how to think about efficiency.

Self-Check

"What if we changed the ternary expression to check every element in a list? How would the time complexity change?"