Wednesday, 7 May 2014

[Python] Ternary Operator

[on_true] if [expression] else [on_false]

x, y = 50, 25
small = x if x < y else y
Before this syntax was introduced in Python 2.5, a common idiom was to use logical operators:
[expression] and [on_true] or [on_false]
However, this idiom is unsafe, as it can give wrong results when on_true has a false boolean value. Therefore, it is always better to use the ... if ... else ... form.

In [9]: %timeit (False and [False] or ['cho'])[0]
10000000 loops, best of 3: 113 ns per loop

In [10]: %timeit False if False else 'cho'
10000000 loops, best of 3: 34 ns per loop
Như kết quả ở trên, dùng Ternary Operation hỗ trợ từ python2.5 có tốc độ nhanh hơn kiểu hack and-or khá nhiều (như ở trên là hơn 3 lần)