Ternary Operator in Python
Conditional expressions (sometimes called a “ternary operator”) have the lowest priority of all Python operations. Ternary operators evaluate something based on a condition being true or false. It was added to Python in version 2.5.
It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.
Syntax :
[on_true] if [expression] else [on_false] expression : conditional_expression | lambda_expr
- Simple Method to use ternary operator:
Python
# Program to demonstrate conditional operator a, b = 10 , 20 # Copy value of a in min if a < b else copy b min = a if a < b else b print ( min ) |
Output:
10
Explanation: 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.
Using tuples, Dictionary, and lambda
Python
# Python program to demonstrate ternary operator a, b = 10 , 20 # Use tuple for selecting an item # (if_test_false,if_test_true)[test] # 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 print ( (b, a) [a < b] ) # Use Dictionary for selecting an item # if [a < b] is true then value of True key will print # else if [a<b] is false then value of False key will print print ({ True : a, False : b} [a < b]) # lambda is more efficient than above two methods # because in lambda we are assure that # only one expression will be evaluated unlike in # tuple and Dictionary print (( lambda : b, lambda : a)[a < b]()) |
Output:
10 10 10
Time Complexity: O(1)
Auxiliary Space: O(1)
- Ternary operator can be written as nested if-else:
Python
# Python program to demonstrate nested ternary operator 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" ) |
Time Complexity: O(1)
Auxiliary Space: O(1)
The above approach can be written as:
Python
# Python program to demonstrate nested ternary operator 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
Time Complexity: O(1)
Auxiliary Space: O(1)
- To use print function in ternary operator be like:-
Example: Find the Larger number among 2 using ternary operator in python3
Python3
a = 5 b = 7 # [statement_on_True] if [condition] else [statement_on_false] print (a, "is greater" ) if (a>b) else print (b, "is Greater" ) |
Output:
7 is Greater
Time Complexity: O(1)
Auxiliary Space: O(1)
Important Points:
- First the given condition is evaluated (a < b), then either a or b is returned based on the Boolean value returned by the condition
- Order of the arguments in the operator is different from other languages like C/C++ (See C/C++ ternary operators).
- Conditional expressions have the lowest priority amongst all Python operations.
Method used prior to 2.5 when the ternary operator was not present
In an expression like the one given below, the interpreter checks for the expression if this is true then on_true is evaluated, else the on_false is evaluated.
Syntax :
'''When condition becomes true, expression [on_false] is not executed and value of "True and [on_true]" is returned. Else value of "False or [on_false]" is returned. Note that "True and x" is equal to x. And "False or x" is equal to x. ''' [expression] and [on_true] or [on_false]
Example :
Python
# Program to demonstrate conditional operator a, b = 10 , 20 # If a is less than b, then a is assigned # else b is assigned (Note : it doesn't # work if a is 0. min = a < b and a or b print ( min ) |
Output:
10
Time Complexity: O(1)
Auxiliary Space: O(1)
Note : The only drawback of this method is that on_true must not be zero or False. If this happens on_false will be evaluated always. The reason for that is if the expression is true, the interpreter will check for the on_true, if that will be zero or false, that will force the interpreter to check for on_false to give the final result of the whole expression.
This article is contributed by Mayank Rawat and improved by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
using for loop:
To use the ternary operator in a for loop, you can follow these steps:
Use the for statement to loop over the data you want to evaluate.
Use the ternary operator to evaluate each element in the data.
Optionally, print the result of the ternary operator for each element.
In this example, the data to be evaluated is stored in a list called data. The for statement is used to loop over each element in the list. The ternary operator is used to determine if each number is even or odd. The result of the ternary operator is stored in a variable called result. Optionally, the print() statement is used to print the result of the ternary operator for each element in the list.
Python3
# Define the data to be evaluated data = [ 3 , 5 , 2 , 8 , 4 ] # Use a for loop to evaluate each element in the data for num in data: # Use the ternary operator to determine if the number is even or odd result = 'even' if num % 2 = = 0 else 'odd' # Optionally, print the result of the ternary operator for each element print (f 'The number {num} is {result}.' ) |
The number 3 is odd. The number 5 is odd. The number 2 is even. The number 8 is even. The number 4 is even.
Approach:
The code defines a list of integers called data. It then uses a for loop to iterate through each element in the list. For each element, it uses a ternary operator to check if it is even or odd, and saves the result to a variable called result. The code then optionally prints the result of the ternary operator for each element.
Time Complexity:
Both the original code and the alternative code have a time complexity of O(n), where n is the number of elements in the data list. This is because both codes need to iterate through each element in the list to evaluate whether it is even or odd.
Space Complexity:
The original code has a space complexity of O(1), as it only uses a few variables to store the input and the results. The alternative code has a space complexity of O(n), as it creates a new list to store the results of the list comprehension.
Please Login to comment...