Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Python by (46k points)

Can someone use other language constructs to stimulate a ternary operator if python doesn't have one.

3 Answers

+3 votes
by (10.9k points)
edited by

@Ayush Yes, Ternary operator is available in Python from version 2.5. It’s a conditional operator which performs an operation based on a condition being true or false in a single line test instead of multiline if-else complexity. It has the lowest priority of all other python operators.

How did this work before the Python 2.5 version?

[expression] and [for_true] or [for_false]

As you asked when a ternary operator was not present in python before its 2.5 version then that will be checked by the interpreter, if the expression will be true then [for_true] evaluated otherwise [for_false] will be evaluated.

For an example -

x, y = 1,2

minimum = x < y and x or y

print(minimum)

Output: 1

If x is less than y then x will be assigned otherwise y will be assigned. Its main drawback is, this system became failed when x = 0 or false and then it will evaluate [for_false] always. This happens because in any case expression will get true and it will move for [for_true] and if it checks its value is 0 or false then it will also move towards [for_false] to print out the final result.

How this is working after python 2.5 version?.

Expression syntax-

[for_true] if [expression] else [for_false]

Methods to use-

1. Simple method

x, y = 1,2
minimum = x if x < y else y
print(minimum)
Output: 1

2. Direct method ( using tuples,dictionary,lambda)

x, y = 1, 2

print( (y, x) [x < y] )

print({True: x, False: y} [x < y])  

print((lambda: y, lambda: x)[y < x]())

Output:

1

 1

1

Hope you understand.

0 votes
by (106k points)
edited by

You can index into a tuple:

(falseValue, trueValue)[test]

test needs to return True or False.

It might be safer to always implement it as:

(falseValue, trueValue)[test == True]

or you can use the built-in bool() to assure a Boolean value:

(falseValue, trueValue)[bool(<expression>)]

To know more about this you can have a look at the following video tutorial:-

Learn in detail about Python by enrolling in Intellipaat Python Course online and upskill.

0 votes
by (20.3k points)

You can try using like this:

<expression 1> if <condition> else <expression 2>

Let's see an example: 

a = 1

b = 2

1 if a > b else -1 

# Here output will be -1

1 if a > b else -1 if a < b else 0

# Here output will be -1

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Sep 25, 2019 in Python by Sammy (47.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...