Python – Swapping Values of Two Variables


Programming languages like C, C++, C#, Java all have a similar technique of exchanging values of two variables. If the variables are numeric then we can use two variables to exchange the values of two variables. But if the variables contain string data, then we need a third variable (temp).

Python does this very simply. Here is the Python code to exchange the values of two variables, both numeric.

print("Swapping two numbers without using a temporary variable")

x = 32
y = 17
print("Before swap x = ", x)
print("Before swap y = ", y)

x, y = y, x

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

Observe line number 8 in this code. Other languages mentioned above will require a code like this:

temp = x; //save the value of x before overwriting it with another value.

x = y;

y = temp;

In the Python code above, replace x and y with “Intel” and “AMD” and see how values are exchanged.

You will agree that Python has simplicity!

%d bloggers like this: