Friday, May 23, 2014

8:42 PM
Good day!

There are many ways to Swap in Python. Today I'm gonna show you three ways to swap two variables using the Python programming language. It will help you to swap string to string or number to number.

First fire up your python idle, or just type python in your linux terminal shell.

1.) First example below is the Python code to swap that will work both for string and number.

>>> a = "Text1"
>>> b = "Text2"
print "Original: %s %s" % (a,b)
Original: a: Text1 - b: Text2
>>> a,b = b,a
>>> print "Swap: %s %s" % (a,b)
Swap: a: Text2 - b: Text1

http://docs.python.org/2/reference/expressions.html#evaluation-order
Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.


The following expression a,b = b,a. This mechanism has effectively swapped the objects assigned to the identifiers a and b.


2.) Second example, this one will work for number swap. Also work for string swap, if the both string length is same. This swap operation is done using bitwise XOR operation. Similar for other language, python also support XOR operation.

>>> a = 100
>>> b = 200
>>> print "Original: %s %s" % (a,b)
Original: 100 200
>>> a = a ^ b
>>> b = a ^ b
>>> a = a ^ b
>>> print "Swap: %s %s" % (a,b)
Swap: 200 100

3.) Third, this one will only work for number swap. Not for text swap.

>>> a = 123
>>> b = 999
>>> print "Original %s %s" % (a,b)
Original 123 999
>>> a = a + b
>>> b = a - b
>>> a = a - b
>>> print "Swap: %s %s" %(a,b)
Swap: 999 123


Finally, since you are using python, I suggest you use the first method as it is simplest way.

0 comments:

Post a Comment