Ternary conditional expression in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
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?"
Practice
x if condition else y do in Python?Solution
Step 1: Understand the ternary syntax
The expressionx if condition else ymeans Python checks thecondition.Step 2: Determine the returned value
Ifconditionis True, it returnsx; if False, it returnsy.Final Answer:
Returnsxifconditionis True, otherwise returnsy. -> Option CQuick Check:
True condition = x, False condition = y [OK]
- Confusing the order of true and false values
- Thinking it always returns the first value
- Assuming it raises errors on false condition
Solution
Step 1: Recall Python ternary syntax
Python uses the formatx if condition else yfor ternary expressions.Step 2: Compare options
x if condition else y matches Python syntax exactly; others use syntax from other languages or incorrect forms.Final Answer:
x if condition else y -> Option DQuick Check:
Python ternary = x if condition else y [OK]
- Using ?: like in other languages
- Writing 'if condition then' which is invalid
- Swapping the order of parts
age = 20 status = "Adult" if age >= 18 else "Minor" print(status)
Solution
Step 1: Evaluate the condition
The conditionage >= 18is True because age is 20.Step 2: Determine the value assigned
Since condition is True,statusis assigned "Adult".Final Answer:
Adult -> Option AQuick Check:
age 20 >= 18 is True, so status = Adult [OK]
- Choosing the else value instead of the if value
- Confusing string output with boolean
- Ignoring the condition result
result = "Pass" if score > 50 else "Fail" else "Invalid"
Solution
Step 1: Analyze the ternary expression structure
The expression has twoelsekeywords, which is invalid syntax in Python ternary expressions.Step 2: Understand Python ternary rules
Python ternary expressions allow only oneelsepart; multiple else cause SyntaxError.Final Answer:
SyntaxError due to multiple else keywords -> Option AQuick Check:
Only one else allowed in ternary [OK]
- Trying to chain else without nesting
- Assuming multiple else are allowed
- Ignoring syntax error messages
Solution
Step 1: Understand dictionary comprehension syntax
It must be{key: value for variable in iterable}. The value can use a ternary expression.Step 2: Check ternary expression placement
d = {x: ("Even" if x % 2 == 0 else "Odd") for x in range(1,6)} correctly wraps the ternary expression in parentheses for clarity and correct parsing.Step 3: Identify incorrect options
d = {x: "Even" if x % 2 == 0 "Odd" for x in range(1,6)} misses theelsekeyword, causing SyntaxError; d = {x if x % 2 == 0 else "Odd": x for x in range(1,6)} misplaces ternary in key. d = {x: "Even" else "Odd" if x % 2 == 0 for x in range(1,6)} has invalid syntax.Final Answer:
d = {x: ("Even" if x % 2 == 0 else "Odd") for x in range(1,6)} -> Option BQuick Check:
Use parentheses around ternary in dict comprehension [OK]
- Placing ternary in key instead of value
- Missing parentheses causing syntax errors
- Using else before if in ternary
