Python ? (conditional/ternary) operator for assignments

PythonCLanguage Features

Python Problem Overview


C and many other languages have a conditional (AKA ternary) operator. This allows you to make very terse choices between two values based on the truth of a condition, which makes expressions, including assignments, very concise.

I miss this because I find that my code has lots of conditional assignments that take four lines in Python:

if condition:
    var = something
else:
    var = something_else

Whereas in C it'd be:

var = condition ? something : something_else;

Once or twice in a file is fine, but if you have lots of conditional assignments, the number of lines explode, and worst of all the eye is drawn to them.

I like the terseness of the conditional operator, because it keeps things I deem un-strategic from distracting me when skimming the code.

So, in Python, is there a trick you can use to get the assignment onto a single line to approximate the advantages of the conditional operator as I outlined them?

Python Solutions


Solution 1 - Python

Python has such an operator:

variable = something if condition else something_else

Alternatively, although not recommended (see karadoc's comment):

variable = (condition and something) or something_else

Solution 2 - Python

In older Python code, you may see the trick:

condition and something or something_else

However, this has been superseded by the vastly superior ... if ... else ... construct:

something if condition else something_else

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWillView Question on Stackoverflow
Solution 1 - PythoncarlView Answer on Stackoverflow
Solution 2 - PythonGreg HewgillView Answer on Stackoverflow