In this article, you’ll learn how to use the ternary operator in Python. The ternary operator in Python is simply a shorter way of writing an if and if…else statement. We’ll see its syntax along with some practical examples.
Python Ternary Operator and its Benefits
The Python ternary operator determines if a condition is true or false and then returns the appropriate value in accordance with the result. The ternary operator is useful in cases where we need to assign a value to a variable based on a simple condition, and we want to keep our code more concise — all in just one line of code. It’s particularly handy when you want to avoid writing multiple lines for a simple if-else situation.
Syntax of Ternary Operator in Python
Syntax: [on_true] if [expression] else [on_false]
expression: conditional_expression | lambda_expr
Simple Method to Use Ternary Operator
In this example, we are comparing and finding the minimum number by using the ternary operator. The expression min is used to print a or b based on the given condition. For example, if a is less than b then the output is a, if a is not less than b then the output is b.
Python3
a, b = 10, 20
min = a if a < b else b
print(min)
|
Ternary Operator Examples
Here we will see the different example to use Python Ternary Operator:
- Ternary Operator in Python If-Else
- Python Ternary Operator using Tuples
- Python Ternary Operator using Dictionary
- Python Ternary Operator using Lambda
- Print in if Ternary Operator
- Limitations of Python Ternary Operator
Ternary Operator in Python If-Else
Example: Using Native way
Python program to demonstrate nested ternary operator. In this example, we have used simple if-else without using ternary operator.
Python3
a, b = 10, 20
if a != b:
if a > b:
print("a is greater than b")
else:
print("b is greater than a")
else:
print("Both a and b are equal")
|
Output
b is greater than a
Example: Using Ternary Operator
In this example, we are using a nested if-else to demonstrate ternary operator. If a and b are equal then we will print a and b are equal and else if a>b then we will print a is greater than b otherwise b is greater than a.
Python3
a, b = 10, 20
print ("Both a and b are equal" if a == b else "a is greater than b"
if a > b else "b is greater than a")
|
Output
b is greater than a
Python Ternary Operator using Tuples
In this example, we are using tuples to demonstrate ternary operator. We are using tuple for selecting an item and if [a<b] is true it return 1, so element with 1 index will print else if [a<b] is false it return 0, so element with 0 index will print.
Python3
a, b = 10, 20
print( (b, a) [a < b] )
|
Output:
10
Python Ternary Operator using Dictionary
In this example, we are using Dictionary to demonstrate ternary operator. We are using tuple for selecting an item and if [a<b] is true it return 1, so element with 1 index will print else if [a<b] is false it return 0, so element with 0 index will print.
Python3
a, b = 10, 20
print({True: a, False: b} [a < b])
|
Python Ternary Operator using Lambda
In this example, we are using Lambda to demonstrate ternary operator. We are using tuple for selecting an item and if [a<b] is true it return 1, so element with 1 index will print else if [a<b] is false it return 0, so element with 0 index will print.
Python3
a, b = 10, 20
print((lambda: b, lambda: a)[a < b]())
|
Print in if Ternary Operator
In this example, we are finding the larger number among two numbers using ternary operator in python3.
Python3
a=5
b=7
print(a,"is greater") if (a>b) else print(b,"is Greater")
|
Limitations of Python Ternary Operator
Python ternary is used to write concise conditional statements but it too have some limitations.
- Readability: Ternary operator can make simple conditional expressions more concise, it can also reduce the readability of your code, especially if the condition and the expressions are complex.
- Potential for Error: Incorrect placement of parentheses, missing colons, or incorrect order of expressions can lead to syntax errors that might be harder to spot.
- Debugging: When debugging, it might be harder to inspect the values of variables involved in a complex ternary expression.
- Maintenance and Extensibility: Complex ternary expressions might become harder to maintain and extend especially when the codebase grows.
- Can’t use assignment statements: Each operand of the Python ternary operator is an expression, not a statement, that means we can’t use assignment statements inside any of them. Otherwise, the program will throw an error.
Example:
Output:
File "Solution.py", line 1
3 if True else x=6
^
SyntaxError: can't assign to conditional expression
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.Dive into the future of technology - explore the
Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
28 Aug, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...