Home > OS >  Python IF statement to a single line
Python IF statement to a single line

Time:12-07

Is it possible to put this code into a single line?

if x == 0:
   a  = j["sum"] 
elif x == 1:
   b  = j["sum"] 

e.e. :D

This is not a working example just for demonstration purposes

a  = j["sum"] if x == 0 else b  = j["sum"] 

CodePudding user response:

You can do it this way if you have Python 3.8 or later for the assignment expression operator :=:

(a := a   j["sum"]) if x == 0 else (b := b   j["sum"]) if x == 1 else None

but really the original is best. It's preferable that code is clear and straightforward.

CodePudding user response:

I may suggest you this one-line dual assignment:

a, b = a   (j["sum"] if x == 0 else 0), b   (j["sum"] if x == 1 else 0)

But you can also use the old good semi-colon to perform two instructions on one line:

a  = (j["sum"] if x == 0 else 0); b  = (j["sum"] if x == 1 else 0)

CodePudding user response:

I would strongly discourage it, but I guess one could use boolean true as the multiplication identity to do:

a, b = a   (x==0) * j["sum"], b   (x==1) * j["sum"]

This seems to work as I expect in a little loop

a=100
b=200
jsum=10

for x in range(3):
    a, b = a   (x==0) * jsum, b   (x==1) * jsum
    print(a, b)

Giving:

110 200
110 210
110 210

CodePudding user response:

While I would not code like this myself, one might throw caution to the wind and leverage exec():

exec(f"{['a','b'][x]}  = j['sum']" if x in [0,1] else "pass")

Note, if you know x is always either 0 or 1 this would simplify to:

exec(f"{['a','b'][x]}  = j['sum']")

Your pseudo-code solution suggests that might be so but your questions suggests it is not.

example:

a=100
b=200
jsum=10

for x in range(3):
    exec(f"{['a','b'][x]}  = jsum" if x in [0,1] else "pass")
    print(a, b)

giving:

110 200
110 210
110 210

CodePudding user response:

You may use conditional expression as an alternative:

X if condition else Y

Like this:

X if condition else (X if condition else Y)

But for second Y you need to handle it.

  • Related