Member-only story

How to Swap the Contents of Two Variables in Python

Alice the Architect
2 min readJan 8, 2025

Here is the problem:

We have two variables, glass1 and glass2. glass1 contains milk, and glass2 contains juice. Write three lines of code to switch the contents of these variables. You are only allowed to use variables to solve this problem.

Hint: Imagine you have a glass of milk and a glass of juice. How would you switch the liquids in real life?

More Hint:

If we have two physical glasses and we want to switch their contents, we would need an extra glass to temporarily hold the contents of one glass. Similarly, in programming, we can create a temporary variable to store the contents of one variable during the switch.

Step-by-Step Explanation of the Code:

temp = glass1

This temporary variable acts like the extra glass in real life, allowing us to swap the contents effectively.

By storing the contents of glass1 in the temp variable, we free up glass1 to hold the contents of glass2. This can be achieved with the following line of code:

glass1 = glass2

Now, glass1 contains what was originally in glass2, and the contents of glass1 are still safely stored in the temp variable.

Finally, we can place the contents of the temp variable (which holds the original contents of glass1) into glass2 using:

glass2 = temp

With these three steps, the contents of glass1 and glass2 are successfully swapped!

glass1 = "milk"
glass2 = "juice"

temp = glass1

glass1 = glass2

glass2 = temp

print(glass1)
print(glass2)

--

--

No responses yet