In some part of my Python program I have a val variable that can be 1 or 0. If it\'s 1 I must change to 0, if it\'s 0 I must change to 1.
How do you do it in a Pytho
The most pythonic way would probably be
int(not val)
But a shorter way would be
-~-val
To expand upon the answer by "YOU", use:
int(not(val))
Examples:
>>> val = 0
>>> int(not(val))
1
>>> val = 1
>>> int(not(val))
0
Note that this answer is only meant to be descriptive, not prescriptive.
Here's a simple way:
val = val + 1 - val * 2
For Example:
If val is 0
0+1-0*2=1
If val is 1
1+1-1*2=0
Function with mutable argument. Calling the swaper()
will return different value every time.
def swaper(x=[1]):
x[0] ^= 1
return x[0]
(0,1)[not val] flips the val from 0 to 1 and vice versa.
Your way works well!
What about:
val = abs(val - 1)
short and simple!