Reputation: 135
I was fiddling with one line if and for statements in python and ran across the following problem:
I can make something like the following work:
state = 1 if state == 4 else 2
But I want to use = and += in the same context, something like this:
state = 1 if state == 4 else state+=1
How can I implement this in one line?
Upvotes: 2
Views: 3240
Reputation: 306
using lambda:
state = (lambda n:[n+1,0][n==4] )(state)
so, in essence:
[n+1,0][1]
# True(1): means get index#1, which is 0
[n+1,0][0]
# False(0):means get index#0, which is n+1
To make it more readable, I will break it down to a function:
def myfunc(n):
ans = [ n+1, 0 ]
if n==4:
return ans[1] # which is the value 0
else:
return ans[0] # which is n+1
state=6
state=myfunc(state) # returns 7
state=4
state=myfunc(state) # returns 0
Upvotes: 0
Reputation: 1990
Just an alternative way to do this is: var = test and "when true" or "when false"
state = state == 4 and 1 or state + 1
The modulus answer is better for this but the above is useful shortcut
Upvotes: 0
Reputation: 15537
This is not possible because assignment is not an expression in Python.
Only expressions have a value in Python, which is different from JavaScript for example - where almost anything, including assignments, have a value.
You can write your program like this, however:
state = 1 if state == 4 else state + 1
This makes the value conditional on the state, not the assignment. It works in your case since the state variable is always assigned a new value.
In the general case, let's say you want to update different variables depending on the current state, you should stick to a regular if
statement. Don't overuse the ternary operator (x if C else y
) - only use it if it makes your code more readable.
Upvotes: 1
Reputation: 31484
You are already assigning the result to state
so you could just:
state = 1 if state == 4 else state + 1
Upvotes: 0
Reputation: 1121476
+=
is not an operator, it is a statement. You cannot use statements in an expression.
Since state
is an integer, just use +
, which is an operator:
state = 1 if state == 4 else state + 1
The end result is exactly the same as having used an +=
in-place addition.
Better still, use the %
modulus operator:
state = (state % 4) + 1
which achieves what you wanted to achieve in the first place; limit state
to a value between 1
and 4
.
Upvotes: 6