Monday, 25 July 2022

Python ternary operation (? ' ' : ' ' )

 Python does not have ternary operation (condtion ) ? TRUE_clause : FALSE_clause


but can use a typo instead 

https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator


You can index into a tuple:

(falseValue, trueValue)[test]

test needs to return True or False.


It might be safer to always implement it as:

(falseValue, trueValue)[test == True]


or you can use the built-in bool() to assure a Boolean value:

(falseValue, trueValue)[bool(<expression>)]

No comments:

Post a Comment