This recipe shows how to swap the values of two variables without making use of a third, temporary variable. The traditional method of swapping two variables is using a temp variable.
The first method shown here, swaps two variables an and b without using a temp variable. The variables a and b are integers:
a = 1, b = 2
Prints original values of a and b, i.e. 1 and 2:
print a, b a = a + b b = a - b a = a - b
Prints swapped values of a and b, i.e. 2 and 1:
print a, b
The above swap method, using arithmetic expressions, will not work for non-numeric data types, and may also not work (at least in some cases) for floats. But the method below should work for any type of Python variable:
It even works for function objects. If you have:
def foo(): print "This is foo()." def bar(): print "This is bar()."
foo, bar = bar, foo
then see what happens to values foo and bar, when you do:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
First method of swapping, using arithmetic expressions, reqires the variable being swapped to be of numeric type, specifically integer: a = 1 b = 2 # Prints original values of a and b, i.e. 1 and 2: print a, b # Now the swap, using some additions and subtractions. a = a + b b = a - b a = a - b# Prints swapped values of a and b, i.e. 2 and 1: print a, b Second method is simpler, and can work for more types of Python objects, using parallel assignment: a, b = b, a
The second solution shown above, works for any type of Python object, not just numeric objects, so is preferable. Also, it avoids unnecessary computation that the first solution does - additions and subtractions.
More details and output at this post: