Ternary Operator in Python (original) (raw)

Last Updated : 29 May, 2026

Ternary operator perform conditional checks and assign values or execute expressions in a single line. It is also known as a conditional expression because it evaluates a condition and returns one value if the condition is True and another if it is False.

Let’s start with an example to determine whether a number is even or odd:

Python `

n = 5 res = "Even" if n % 2 == 0 else "Odd" print(res)

`

**Explanation:

Ways to Use Ternary Operator

1. Nested If-Else

Ternary operator can also be used in Python nested if-else statement. We can nest ternary operators to evaluate multiple conditions in a single line.

**Syntax:

value_if_true if condition else value_if_false

Python `

num = -5 res = "Positive" if num > 0 else "Negative" if num < 0 else "Zero" print(res)

`

**Explanation:

2. Tuple

Ternary operator can also be written by using Python tuples. The tuple indexing method is another way to select between two values using a boolean index. Unlike the ternary operator, both tuple elements are evaluated before the selection is made.

**Syntax:

(condition_is_false, condition_is_true)[condition]

Python `

n = 7 res = ("Odd", "Even")[n % 2 == 0] print(res)

`

**Explanation: The condition num % 2 == 0 evaluates to False (index 0), so it selects "Odd".

3. Dictionary

A dictionary can be used to map conditions to values, providing a way to use a ternary operator with more complex conditions.

**Syntax:

condition_dict = {True: value_if_true, False: value_if_false}

Python `

a = 10 b = 20 m1 = {True: a, False: b}[a > b] print(m1)

`

**Explanation: This uses a dictionary where the key is True or False based on the condition a > b. The corresponding value (a or b) is then selected.

4. Using Ternary Operator Inside Lambda Function

Lambdas can be used in conjunction with the ternary operator for inline conditional logic.

**Syntax:

lambda x: value_if_true if condition else value_if_false

Python `

a = 10 b = 20 m1 = (lambda x, y: x if x > y else y)(a, b) print(m1)

`

**Explanation: This defines an anonymous function (lambda) that takes two arguments and returns the larger one using the ternary operator. It is then called with a and b.

5. Print Function

The ternary operator can also be directly used with the Python print statement.

**Syntax:

print(value_if_true if condition else value_if_false)

Python `

a = 10 b = 20

print("a is greater" if a > b else "b is greater")

`