phsyron
phsyron

Reputation: 540

Python assignment to conditional LHS

I know about

a = val1 if condition else val2

but is there a way to do something like

a if condition else b = val

which throws a SyntaxError (which is understandable I suppose)

I would use a conditional,

if condition:
    a = val
else:
    b = val

but I hate having the same piece of code (here, the right-hand-side) in my program twice (in my real code, val is a non-trivial expression). I know I can just make a dummy variable to hold that piece, but that seems un-idiomatic.

It also occurred to me to do a tuple

ba = (b,a)
ba[bool(condition)] = val
b, a = ba

but that also seems very non-idiomatic.

Is there another way that I'm not thinking of?

Upvotes: 2

Views: 407

Answers (4)

nino_701
nino_701

Reputation: 692

If a and b have some previous values you can simply write:

a, b = (a, val) if condition else (val, b)

Else you can write

a, b = (None, val) if condition else (val, None)

Upvotes: 0

TigerhawkT3
TigerhawkT3

Reputation: 49330

You can use a function to encapsulate the logic and unpack it back to the variables you're interested in:

def decider(x, y, condition, val):
    if condition:
        return val, y
    return x, val

a, b = decider(a, b, cond, value)

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96346

It's doable in one line with tuples:

a,b = val if cond else a, val if not cond else b

But please don't use it, it's ugly and a lot more complicated that a plain if statement.

Upvotes: 1

Gareth McCaughan
Gareth McCaughan

Reputation: 19981

No, you can't do that. Make another variable to hold val and use if. Simple is good.

Upvotes: 1

Related Questions