1

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)
3
  • If you could use fun(3) in the theoretical one-liner, you could use fun(3) in x = fun(3). Then, since you know 3 == 3, m = 3 if fun(3) == 3 else 4. If this doesn’t work for your actual situation, please pick something representative of your actual situation. Commented Sep 20, 2017 at 2:06
  • 1
    Assignment is a statement, not an expression in Python. The code seems concise enough. Commented Sep 20, 2017 at 2:08
  • " Would this work? " ~ Why don't you try out yourself? (It won't. juanpa.arrivillaga said it right) Commented Sep 20, 2017 at 3:45

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

And if you enjoy abusing for loops in ugly ways, I recommend the intellectual exercise of trying to get anything serious done in a Windows batch file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.