DingLi
DingLi

Reputation: 821

Python, Concise code on if else statement with function call?

I am wondering if there is a more concise code on the below snippet.

def fun(x):
    return x + 2
a = 3
x = fun(a)
m = x if x == 3 else 4

print(m)

Would this work?

def fun(x):
    return x + 2

m = (x = fun(3)) if x == 3 else 4

print(m)

Upvotes: 1

Views: 383

Answers (2)

jez
jez

Reputation: 15349

It can be done, but it's not very readable/maintainable code:

m, = [ x if x == 3 else 4   for x in [fun(a)] ]

The assignment to x persists after it is used as the loop variable inside the list comprehension. Therefore, this one-liner has the effect of assigning both m and x in the way that you want.

Upvotes: 2

Mark Ransom
Mark Ransom

Reputation: 308111

If you're determined to make it a one-liner, and for some reason you can only call fun once, you can use a lambda function:

m = (lambda x: x if x == 3 else 4)(fun(a))

You can see that this isn't terribly readable, and I wouldn't recommend it.

Your trial code wouldn't work because you can't do assignment in an expression.

Upvotes: 3

Related Questions