HomeUncategorizedπŸ” Swap Variables in Python – All Possible Methods Explained

πŸ” Swap Variables in Python – All Possible Methods Explained

Swapping variables is one of the most common beginner exercises in programming. Whether you’re preparing for interviews, coding challenges, or just practicing Python, it’s essential to know the different ways to swap two variables.

In this blog, we’ll explore all the major methods to swap variables in Pythonβ€”ranging from the classic to the most Pythonic ways.


πŸ”Ή Scenario

Let’s say we have two variables:

glass1 = "milk"
glass2 = "juice"

Our goal is to swap their contents so that:

glass1 ➝ "juice"
glass2 ➝ "milk"

βœ… 1. Using a Temporary Variable

The most basic method, used in almost every language:

temp = glass1
glass1 = glass2
glass2 = temp

🟒 Pros: Easy to understand
πŸ”΄ Cons: Requires an extra variable


βœ… 2. Pythonic Way – Tuple Unpacking

Python allows swapping in a single line using tuple unpacking:

glass1, glass2 = glass2, glass1

🟒 Pros: Clean, readable, no temporary variable needed
πŸ”΄ Cons: Might confuse absolute beginners


βœ… 3. Using a List

Swap values using a list and index positions:

glasses = [glass1, glass2]
glasses[0], glasses[1] = glasses[1], glasses[0]
glass1, glass2 = glasses

🟒 Pros: Useful when working with list-based data
πŸ”΄ Cons: Slightly overkill for just two variables


βœ… 4. Using a Dictionary

Although not common, dictionaries can be used to swap:

glasses = {"g1": glass1, "g2": glass2}
temp = glasses["g1"]
glasses["g1"] = glasses["g2"]
glasses["g2"] = temp
glass1 = glasses["g1"]
glass2 = glasses["g2"]

🟒 Pros: Good for more than 2 variables
πŸ”΄ Cons: Verbose for this simple case


βœ… 5. Using a Custom Swap Function

We can also define a reusable function to swap:

def swap(a, b):
    return b, a

glass1, glass2 = swap(glass1, glass2)

🟒 Pros: Clean logic, reusable
πŸ”΄ Cons: Slightly more code for a basic swap


❌ 6. Using Arithmetic Operations (Not for Strings)

This works only for numbers, not strings like “milk”/”juice”:

a = 5
b = 10

a = a + b
b = a - b
a = a - b

🟒 Pros: No extra variables
πŸ”΄ Cons: Not suitable for non-numeric types; risk of overflow


βœ… 7. Using Bitwise XOR (For Integers Only)

Also works only for integers:

a = 5
b = 10

a = a ^ b
b = a ^ b
a = a ^ b

🟒 Pros: No extra memory
πŸ”΄ Cons: Confusing; not for strings or floats


βœ… 8. Using Stack (Advanced)

This can be demonstrated using a list as a stack:

stack = []
stack.append(glass1)
stack.append(glass2)

glass1 = stack.pop()
glass2 = stack.pop()

🟒 Pros: Simulates real-world stack behavior
πŸ”΄ Cons: Over-complicated for simple variable swap


βœ… Summary Table

MethodWorks for StringsExtra VariablePythonicLine Count
Temporary Variableβœ…βœ…βŒ3
Tuple Unpackingβœ…βŒβœ…1
List Indexingβœ…βœ…βœ…3+
Dictionaryβœ…βœ…βŒ4+
Custom Functionβœ…βŒβœ…2
Arithmetic (only numbers)❌❌❌3
Bitwise XOR (integers)❌❌❌3
Stack/List push-popβœ…βœ…βœ…3+

🧠 Final Thoughts

Swapping variables is a fundamental concept that helps you understand memory, variable references, and Python’s flexibility. Master all methods to sharpen your understanding, and use the most readable or efficient one based on your context.

πŸ’‘ Tip: In real-world Python code, always prefer glass1, glass2 = glass2, glass1 unless you have a special case.


Share:Β 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *