Python – Swapping Values of Two Variables – Yet Another Way


In another article here, I have discussed how values of two variables can be exchanged without using a third variable.

Here is another way in which values can be exchanged. This way will work only with integers. Here is the Python code:

print("Swapping two numbers without using a temporary variable")
 
x = 32
y = 17
print("Before swap x = ", x)
print("Before swap y = ", y)
 
x = x - y
y = y + x
x = y - x

print("After swap x = ", x)
print("After swap y = ", y)

Lines 8, 9 and 10 in the above code are where the “magic” happens. Try this program by taking negative values of one of the variables, and then both variables. Unlike the earlier way, this program will not work if one or both variables has string value.

%d bloggers like this: