Wednesday, October 06, 2010

The ? : operator in Python

We're all familiar with the "? :" operator from Java and other languages, which can be useful in some cases, for example:
max = (x > y) ? x : y
While Python doesn't have this operator built-in, one can definitely mock the behavior:
max = x > y and x or y
How it works?
The expression is parsed left to right, so first "x > y" is parsed.
If "x > y" yields "True", the "and x" part is parsed and since "True and x" yields x, this is the result of the entire expression (no need to parse the right side of the "or" since the left side was successful).
if "x > y" yields "False", then the "or y" part is parsed, resulting y.

I like it :)

No comments: