To swap two values, save the first in a temporary variable, assign the second to the first, and then restore the saved value into the second. Python also supports simultaneous assignment with a, b = b, a.
A simple example
Exchange two values
Start witha = 1, b = 2
Do thisKeep a copy of the first value
Resulta = 2, b = 1
Save 1, move 2 into a, then move the saved 1 into b. This preserves both original values.
Swap two presentation slots
Start withSlot 1 for Ada, slot 2 for Sam
Do thisExchange the two assignments
ResultSlot 1 for Sam, slot 2 for Ada
Keeping one assignment while moving the other prevents either student from disappearing from the schedule.
Temporary variable
Arithmetic operation
Exclusive OR operation (i.e. XOR)
The arithmetic examples assume the intermediate results fit the numeric type. Multiplication followed by division also requires nonzero divisors. XOR swapping applies to integers stored in distinct variables.
Swap two values with a temporary variable
Python source code
class SwapExample:
def __init__(self):
pass
def swapNumbers(self):
a = 3
b = 6
print("The value of a before swap is " + str(a))
print("The value of b before swap is " + str(b))
# Swapping of two numbers using temp variable
temp = a
a = b
b = temp
print("The value of a after swap is " + str(a))
print("The value of b after swap is " + str(b))
obj = SwapExample()
obj.swapNumbers()
Output
The value of a before swap is 3
The value of b before swap is 6
The value of a after swap is 6
The value of b after swap is 3
Advertisements
Swap two numbers with addition and subtraction
Python source code
class SwapExample:
def __init__(self):
pass
def swapNumbers(self):
a = 3
b = 6
print("The value of a before swap is " + str(a))
print("The value of b before swap is " + str(b))
# Swapping of two numbers using arithmetic operations
a = a + b
b = a - b
a = a - b
print("The value of a after swap is " + str(a))
print("The value of b after swap is " + str(b))
obj = SwapExample()
obj.swapNumbers()
Output
The value of a before swap is 3
The value of b before swap is 6
The value of a after swap is 6
The value of b after swap is 3
Swap two integers with bitwise XOR
Python source code
class SwapExample:
def __init__(self):
pass
def swapNumbers(self):
a = 3
b = 6
print("The value of a before swap is " + str(a))
print("The value of b before swap is " + str(b))
# Swapping of two numbers
# using exclusive OR operation (i.e. XOR)
a = a ^ b
b = a ^ b
a = a ^ b
print("The value of a after swap is " + str(a))
print("The value of b after swap is " + str(b))
obj = SwapExample()
obj.swapNumbers()
Output
The value of a before swap is 3
The value of b before swap is 6
The value of a after swap is 6
The value of b after swap is 3