Reputation: 9
I need a code to swap the value of two variables without using third variable but only with AND, OR & NOT operators
I have tried it but i always lost one value
Exact code
Upvotes: 0
Views: 84
Reputation: 24691
As the pythonic approach and the arithmetic approach have already been submitted as answers, I will present the bitwise xor
approach, as outlined on wikipedia:
a = a ^ b
b = b ^ a
a = a ^ b
Of course, you can simplify that if you want:
a ^= b
b ^= a
a ^= b
It's really important to note that this only works on things that can be represented bitwise, like integers. Python will raise an error if you try it on floats or strings or most other datatypes.
Upvotes: 0
Reputation: 9575
For integers, you can use xor:
x = x ^ y
y = x ^ y
x = x ^ y
But otherwise you should just stick to standard swapping practice:
x, y = y, x
The code above creates the tuple (y, x)
and unpacks it to x
and y
Upvotes: 1
Reputation: 19264
>>> a = 5
>>> b = 6
>>> a+=b
>>> b = a - b
>>> a = a - b
>>> a
6
>>> b
5
>>>
Upvotes: 0