Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Conditional Expression in Python

📅 2012-Apr-24 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ conditional expression, python, ternary operator ⬩ 📚 Archive

Python does not have the ternary operator seen in C-like languages. Instead it has the conditional expression. It is of the form X if C else Y:

i = 99
x = True if 99 == i else False
# True

In X if C else Y, either or both of X and Y can themselves be conditional expressions:

i = 99
j = 42
x = ( list() if 42 == j else tuple() ) if 99 == i else False
# []

The conditional expression can be used as a cool and easy-to-read alternative to a chain of if-else statements:

# Peter Norvig's example in Udacity CS212
return (
    9 if (5, ) == counts else
    8 if straight and flush else
    7 if (4, 1) == counts else
    6 if (3, 2) == counts else
    5 if flush else
    4 if straight else
    3 if (3, 1, 1) == counts else
    2 if (2, 2, 1) == counts else
    1 if (2, 1, 1, 1) == counts else
    0)

For more info on conditional expressions, see Expressions and PEP 308.

Tried with: Python 3.2.2


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧