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()."
and then:
foo(), bar()
and then:
foo, bar = bar, foo
then see what happens to values foo and bar, when you do:
foo() bar()
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:
http://jugad2.blogspot.in/2015/09/swapping-two-variables-without-using.html
But Why? Take easy to understand code and obfuscate it?
@Ron Fox: Good question. To answer, and to provide some context:
2: Context: This is an old trick, I first saw it in a class when learning C or Pascal years ago. Those languages did/do not have the parallel assignment feature of Python (a, b = b, a) (though C has chain assignment, which is different, e.g.: a = b = c = 0). Also, memory was more constrained in those days, so such tricks were in fashion then.
Hope that clears things up :)