DEV Community

Cover image for Ternary operator in python
Ajith R
Ajith R

Posted on

Ternary operator in python

Ternary operator provides short and concise way to write the conditional statements and allows to evaluate and test the condition in a single line of code.

Syntax:
true_value if condition else false_value

Example:

# initialize values 
x, y = 5, 10
# expression with ternary operator 
largest = y if x<y else x
# print largest result
 print(largest)
Output
10
Enter fullscreen mode Exit fullscreen mode

Like as ternary operator using if..else we can also implement the same using list, tuple, dictionary and lambda.

Using List

Syntax:
[false_value, true_value] [condition]

# initialize values 
x, y = 5, 10
# expression using List
 largest [x, y][x < y] =
# print largest result 
print(largest)
Output
10
Enter fullscreen mode Exit fullscreen mode

Using Dictionary
Syntax:
{True: true_value, False: false_value} [condition]

# initialize values
 x, y = 5, 10
# expression using Dictionary
 largest = {True: y, False: x}[x < y]
# print largest result 
print(largest)
Output
10
Enter fullscreen mode Exit fullscreen mode

Using Lambda
Syntax:
(lambda: false_value, lambda: true_value) [condition] ()

# initialize values
x, y = 5, 10
# expression using lambda 
largest = (lambda: x, lambda: y)[x<y](
# print largest result
 print(largest)
Output
10
Enter fullscreen mode Exit fullscreen mode

Top comments (0)