Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign two variables with ternary operator

Is there a way to do variable assignments(as shown below) using ternary operators in python:

if(x>1):
    y="yes"
else:
    z="yes"

Something like (x='yes') if(x>1) else (z='yes'), but this gives an error. Is there any other way to do this?

I know single variable assignments can be done like this: x="yes" if(l==0) else "no"

Edit: Assume x, y & z are assigned with some value before this is run.

like image 725
Ani Menon Avatar asked May 28 '16 11:05

Ani Menon


2 Answers

You can use the following hack, which employs tuple unpacking:

y, z = ('yes', z) if x > 1 else (y, 'yes')

Don't miss those parentheses.

I wouldn't really recommend using this as it is harder to understand, has one redundant assignment statements, and uses unpacking unnecessarily. I'd recommend going for the normal if statement wherever you can.

This is what it would be with normal ifs:

if x > 1:
    y = 'yes'
    z = z
else:
    y = y
    z = 'yes'
like image 192
EvilTak Avatar answered Sep 18 '22 01:09

EvilTak


No, you can't do that. You can only have expressions, not statements, inside the ternary. print works because (in Python 3 at least) it is a function call, therefore an expression; but assignment is always a statement.

like image 26
Daniel Roseman Avatar answered Sep 22 '22 01:09

Daniel Roseman