Praffull Kuvalekar
Praffull Kuvalekar

Reputation: 9

What's the code to swap variable values using AND, OR, NOT

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

Answers (4)

Green Cloak Guy
Green Cloak Guy

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

Alec
Alec

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

ooo
ooo

Reputation: 743

a = 1
b = 2

# swap
a, b = b, a

Upvotes: 1

A.J. Uppal
A.J. Uppal

Reputation: 19264

>>> a = 5
>>> b = 6
>>> a+=b
>>> b = a - b
>>> a = a - b
>>> a
6
>>> b
5
>>> 

Upvotes: 0

Related Questions