There are many ways to make a ternary operator in Python but there exists a one-liner if-else statement that is usually called the ternary or conditional operator in Python. There are more ways that can act as or simulate a ternary operator in Python. Let’s explore most of them today.
1. if-else
Syntax:
<expression 1> if <condition> else <expression 2>
Explanation:
if the condition
is true then expression 1
will be evaluated else expression 2
will be evaluated.
Example 1:
print(5 if 7>6 else 4)
Here, condition
is 7>6, expression 1
is 5, and expression 2
is 4
Output:
5
Example 2:
# assigning variable according to condition
a = 5 if 7>6 else 4
print(a)
Output:
5
2. Using List
Syntax:
[expression 1, expression 2][condition]
if the condition
is true, expression 2
will be evaluated else expression 1
will be evaluated.
Example 1:
a = 45>55
b = ['on_false', 'on_true'][a]
print(b)
Output:
on_false
Example 2:
a = 55 > 45
b = ['expression 1', 'expression 2'][a]
print(b)
Output:
expression 2
3. Using Tuple
Syntax:
(expression 1, expression 2)[condition]
Explanation:
if the condition
is true, expression 2
will be evaluated else expression 1
will be evaluated.
Example 1:
a = True
b = ('expression 1', 'expression 2')[a]
print(b)
Output:
expression 2
Example 2:
a = False
b = ('expression 1', 'expression 2')[a]
print(b)
Output:
expression 1
4. Using dictionary
Syntax:
{True: 'on_true', False: 'on_false'}[condition]
Explanation:
if the condition
is true True: 'on_true'
will be evaluated else False: 'on_false'
.
Example 1:
a = 45 > 55
b = {True: 'true', False: 'false'}[a]
print(b)
Output:
false
Example 2:
a = 55 > 45
b = {True: 'true', False: 'false'}[a]
print(b)
Output:
true
5. Using tuple and lambda
According to this solution on StackOverflow, there may be some bugs in the 2nd, 3rd, and 4th methods so using the lambda function will be a good option.
Syntax:
(lambda: 'falseValue', lambda: 'trueValue')[condition]()
6. Logical and
and or
Syntax:
condition and on_true or on_false
Example 1:
a = True
b = a and 'on_true' or 'on_false'
print(b)
Output:
on_true
Example 2:
a = 45 > 55
b = a and 'true' or 'false'
print(b)
Output:
false
I hope these methods are enough if you want to know how to create a ternary operator in Python. If you know more methods of creating a ternary or conditional operator in Python, please use the comments below so that others can discuss them with you.
Thank you for visiting our website.