0

The ternary operator allows testing a condition in a single line replacing the multiline if-else making the code compact.

[on_true] if [expression] else [on_false] 

We can also use the direct Method by using tuples like (b, a) [a < b]. Let's look at an example

ck = True
print(2 if ck else 1)
print((1, 2)[ck])

Here both output is 2. Now, if i change the output 2 & 1/0 Tuple always raise zero division error.

print(2 if ck else 1/0)
print((1/0, 2)[ck])

Same error for (2, 1/0)[ck]. Ternary if-else is showing the correct result under any circumstances but why tuple raise the error 1/0?

mhhabib
  • 2,975
  • 1
  • 15
  • 29
  • 1
    Because tuple initialization is an expression which will be evaluated regardless of which index you want to retrieve from this tuple while ternary operation will evaluate only part which passes condition. If you want an alternative which will work: `ck and 2 or 1/0`. – Olvin Roght Feb 23 '21 at 05:51

2 Answers2

3

Actually, it's very much giving the right result, as per the specifications :-)

In the expression 2 if True else 1/0 (I'm using True here since that's what your ck variable is set to in all cases), 1/0 is never actually evaluated. Although it is in 2 if False else 1/0 so you get the divide-by-zero error in that case. The online docs make this clear (my emphasis):

The expression x if C else y first evaluates the condition, C rather than x. If C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

In other words, only one of the potential expressions is evaluated.

In (1/0, 2)[x] where x may be True or False, the entire tuple (1/0, 2) is created (i.e., both elements) before attempting to select one, so the error occurs regardless of x.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
2

It hasn't been evaluated yet in the first case because ck=True so there's no need to evaluate the else. Whereas in the tuple case it is creating the tuple and then evaluating.

EDIT: Check out this explanation. It is called "lazy evaluation".

PeterT
  • 920
  • 8
  • 20