Ternary Operator Python

As the Python community differentiates between the ternary operator and the if-else condition, the former is said to be a better way of writing conditional statements.

The reason behind using the ternary operator is simple, if-else condition blocks tend to be messy and thus it becomes really a tedious task to write a long series of such blocks for a simple condition.

This operator was added to Python in version 2.5. It simply replaces the multiline If-Else statement with a single line condition.

value_if_true if condition else value_if_false 

As you can see above Conditional expressions in python makes code more compact.

Here are different ways a Ternary operator python can be implemented as:

Simple method of using ternary operators:

Let’s see an example of a simple ternary operator method

x,z=8,5 
print("x" if x>z else "z")
x

If we had to write the same code in an If and else statement it would have looked something like:

x,z=8,5 

 if x>z:        
 print("x") 
else:        
 print("z")

1. Using Python Tuples

Conditional Expressions can be used with tuples

a, b = 8, 10


 print( (b, a) [a < b] )
8

The above code works as the following syntax:

(if_test_is_false, if_test_is_true)[test] 

2. Using Python Dictionaries

Dictionaries are ordered collections of data values that can be changeable but do not allow duplicates. It stores data values in key: value pairs.

Here’s how you can use the ternary python operator with dictionaries in python:

a, b = 7, 10

 print({True: a, False: b} [a < b])
7

3. Using Lambdas

We can use Lambda functions to act as a ternary operator. Lamba function can be more efficient compared to tuples and dictionaries.

a, b = 5, 25

print((lambda: b, lambda: a)[a < b]())
5

Nested Python Ternary Operator

We can chain these operators as nested if-else:

a, b = 35, 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")
a is greater than b

Above were some of the ways ternary operators in python works. This can be a easy way to test code in a compact rather than using If and else statements. Although both has its benefits, its on you to use the one which best suits the situation in the code.

We will be happy to hear your thoughts

      Leave a reply

      Techs Tricks
      Logo
      Reset Password
      Shopping cart