DSM
DSM

Reputation: 101

Python IF statement to a single line

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"] 

Upvotes: 3

Views: 4539

Answers (4)

JonSG
JonSG

Reputation: 13097

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")

or potentially even better (credit to @wjandrea):

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

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

@wjandrea has suggested a nice improvement that produces the same results and is likely faster given the ability to bypass exec() if x is out of range.

a=100
b=200
jsum=10

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

Upvotes: 0

JonSG
JonSG

Reputation: 13097

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

Upvotes: 0

Laurent H.
Laurent H.

Reputation: 6526

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)

Upvotes: 2

sj95126
sj95126

Reputation: 6908

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.

Upvotes: 5

Related Questions