Python Tutorial‎ > ‎

Variable Swap with Two Variables

How to swap the values of two variables using only two variables.
Please note this will only work with numbers.

Say will have two variables, varA and varB; We want the value of varA to equal the value of varB and varB to equal the value of varA.
Now in most programs we would just use a third variable, varC.
With 3 variables it would be as easy as:

3 Variable swap

A = 5
B = 4
C = 5 (A)
A = 4 (B)
B = 5 (C)

varC = varA
varA = varB
varB = varC



With two variables we cannot store the temporary value, so we use the following instead:

varA = varA + varB
varB = varA - varB
varA = varA - varB

In my program you can see that varA stores the value of A and B (Total of both), then varB = the total value - the original varB value. Then varA can be set to the total - the value of varB which now has the original value of varA.

2 variable swap

A = 5
B = 4
A = A + B (5+4 = 9)
B = A - B (9-4 = 5)
A = A - B (9-5 = 4)