Ternary conditional expression in Python - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: A single comparison and return statement.
- How many times: Exactly once per function call.
Since the ternary expression runs just one check, the steps stay the same no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The work does not increase as input grows; it stays constant.
Time Complexity: O(1)
This means the time to run the ternary expression stays the same no matter how big the input is.
[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.
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.
"What if we changed the ternary expression to check every element in a list? How would the time complexity change?"