Code Yarns β€πŸ‘¨β€πŸ’»
Tech Blog ❖ Personal Blog

Python: Ternary Operator / Conditional Expression

πŸ“… 2009-Oct-15 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ conditional expression, python, ternary operator ⬩ πŸ“š Archive

Conditional expression is Python’s version of the C ternary operator (?:)

# Read PEP 308 for this design choice.

# Lots of lines for a simple initialization
alist = []
if solved:
    alist = solvedList
else:
    alist = problemList

# Conditional expression to achieve the above
alist = solvedList if solved else problemList

Β© 2022 Ashwin Nanjappa β€’ All writing under CC BY-SA license β€’ 🐘 @codeyarns@hachyderm.io β€’ πŸ“§