2

I'm trying to write an inline if/else statement that assigns two values based on a single condition. Something to the effect of:

x = y = 0
value = 11
threshold = 5

x, y = x+1, 0 if value <= threshold else x, y = x-1, value

I'd expect this code to result in x = -1 and y = 11. When I run this, I get this error: SyntaxError: cannot assign to literal. I played around with parenthesis, but couldn't get anything to work.

Is there a way to do this? I can work around this, but this would be especially convenient.

1 Answer 1

4

You need parentheses, and the extra x, y = after the else is not needed as well:

>>> x = y = 0
>>> value = 11
>>> threshold = 5
>>>
>>> x, y = (x+1, 0) if value <= threshold else (x-1, value)
>>> x
-1
>>> y
11

Note that without parentheses, you have a 3-tuple on the right side:

>>> x,y = x-1, value if value <= threshold else x+1, 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

It is parsed as: x+1, 0 if value <= threshold else x-1, value

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

1 Comment

@LCVcode The typo is extraneous to the problem. I'll edit it out of both and we can delete these comments.

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.