5

In python, if I use a ternary operator:

x = a if <condition> else b

Is a executed even if condition is false? Or does condition evaluate first and then goes to either a or b depending on the result?

jj172
  • 751
  • 2
  • 9
  • 35

2 Answers2

14

The condition is evaluated first, if it is False, a is not evaluated: documentation.

ducminh
  • 1,312
  • 1
  • 8
  • 17
4

It gets evaluated depending if meets the condition. For example:

condition = True
print(2 if condition else 1/0)
#Output is 2

print((1/0, 2)[condition])
#ZeroDivisionError is raised

No matter if 1/0 raise an error, is never evaluated as the condition was True on the evaluation.

Sames happen in the other way:

condition = False
print(1/0 if condition else 2)
#Output is 2
Rafael
  • 104
  • 8