Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ? (conditional/ternary) operator for assignments [duplicate]

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?

like image 553
Will Avatar asked Jun 22 '10 08:06

Will


People also ask

Does Python have a ternary conditional operator?

Here, Python's ternary or conditional operators are operators that evaluate something based on a condition being true or false. They are also known as conditional expressions.

Can we use assignment operator in ternary operator?

both are fine. invalid lvalue in assignment. which gives error since in C(not in C++) ternary operator cannot return lvalue.

Can ternary operator have multiple conditions?

We can nest ternary operators to test multiple conditions.

Can ternary operator have three conditions?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.


1 Answers

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 
like image 198
carl Avatar answered Oct 11 '22 08:10

carl