5

I have been reading all over the place, including Does Python have a ternary conditional operator?. It is supposed that

result = a if a > b else b

is better code than

result =  a > b and a or b

But no one ever explains why. Will someone please elaborate?

If it's mere readability, then it's really just a matter of preference: some people will like the one and some people will like the other. So my question is: is there some really technical advantage for going one way versus the other.

Community
  • 1
  • 1
learner
  • 11,490
  • 26
  • 97
  • 169

1 Answers1

14

result = a if a > b else b is better because it is always semantically correct. In other words, you will always get what you expect from it, regardless of the value of either a or b. result = a > b and a or b will result in b every time if a is a falsey value (0, None, etc).

Additionally, since a if x else b is a specifically defined language construct, it will typically be easier for other Python developers to understand. Ultimately, anyone reviewing or maintaining your code should have to do as little mental wrangling as possible to understand what's going on.

multipleinterfaces
  • 8,913
  • 4
  • 30
  • 34
  • 3
    Additionally, when I see the first one, I can read it **immediately** without having to try to decipher a bunch of logic ... – mgilson Jan 31 '13 at 14:21