Top-rated recipes tagged "swap"http://code.activestate.com/recipes/tags/swap/top/2015-09-19T19:51:22-07:00ActiveState Code RecipesSwapping two variables without using a third (temporary) variable (Python) 2015-09-19T19:51:22-07:00Vasudev Ramhttp://code.activestate.com/recipes/users/4173351/http://code.activestate.com/recipes/579101-swapping-two-variables-without-using-a-third-tempo/ <p style="color: grey"> Python recipe 579101 by <a href="/recipes/users/4173351/">Vasudev Ram</a> (<a href="/recipes/tags/swap/">swap</a>). </p> <p>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.</p> <p>The first method shown here, swaps two variables an and b without using a temp variable. The variables a and b are integers:</p> <p>a = 1, b = 2</p> <h4 id="prints-original-values-of-a-and-b-ie-1-and-2">Prints original values of a and b, i.e. 1 and 2:</h4> <p>print a, b a = a + b b = a - b a = a - b</p> <h4 id="prints-swapped-values-of-a-and-b-ie-2-and-1">Prints swapped values of a and b, i.e. 2 and 1:</h4> <p>print a, b</p> <p>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:</p> <p>It even works for function objects. If you have:</p> <p>def foo(): print "This is foo()." def bar(): print "This is bar()."</p> <p>and then:</p> <p>foo(), bar()</p> <p>and then:</p> <p>foo, bar = bar, foo</p> <p>then see what happens to values foo and bar, when you do:</p> <p>foo() bar()</p>