160

Many languages have a conditional (AKA ternary) operator. This allows you to make terse choices between two values based on a condition, which makes expressions, including assignments, concise.

My code has conditional assignments:

if condition:
    var = something
else:
    var = something_else

In C it'd be:

var = condition ? something : something_else;

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?

0

2 Answers 2

263

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
Sign up to request clarification or add additional context in comments.

5 Comments

That "variable = condition and something or something_else" doesn't even work. For example, "True and False or True" returns True, whereas "True ? False : True" would return False.
Something or Something_else works fine right? For instance if something was null you'd set it to something_else?
@karadoc right point but bad example&no explanation for the second example: for beginners: if "something" is considered empty/falsy => it is evaluated to False => so you will NEVER get values like 0 (int zero), ""(empty string), [] empty array, False, and other "empty" values => because they evaluate to False => True and False is False :) Some languages even consider "0" (zero as string) as empty value :)
If something is an expression, is it lazily evaluated?
count+=1 if condition else count -= 1 is it possible
22

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

4 Comments

why don't "return if not whatever" work, though?
@Will: Because "return if not whatever" is not syntactically correct Python?
@Will Probably because you don't provide an else part?
You can return 1 if not cond else 2 since that returns the expression 1 if not cond else 2. But you can't just use return if not cond (even with else) since if...else is an expression: it evaluates to a value. You want to use if as control flow which is different. But if not cond: return is ok.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.