Code With Coffie
  • HOME
  • ABOUT US
  • PORTFOLIO
  • JAVASCRIPT
    • Vue.js
  • PHP
    • PHP OOPS
    • LARAVEL
    • WORDPRESS
  • MYSQL
    • DATETIME
  • DSA
    • LEETCODE
  • Home
  • Blog
  • Uncategorized
  • πŸ” Swap Variables in Python – All Possible Methods Explained

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

Jul 06, 2025 by codewithhemu

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:
Previous Article Generate a Fibonacci series using a loop in Python
Next Article Type Error, Type Conversion, and Type Checking in Python
No comments yet! You be the first to comment.

Leave a Reply Cancel reply

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

category

  • DATETIME (6)
  • DJANGO (1)
  • Docker (1)
  • DSA (21)
  • DSA PRACTICE (4)
  • ENGLISH READING (1)
  • JAVASCRIPT (69)
  • LARAVEL (40)
  • LeetCode (1)
  • MYSQL (45)
  • PHP (21)
  • PHP OOPS (16)
  • PROGRAMME (1)
  • PYTHON (7)
  • REACT JS (6)
  • STAR PATTERN PROGRAMME (7)
  • Uncategorized (20)
  • Vue.js (5)
  • WORDPRESS (15)

Archives

  • March 2026
  • October 2025
  • September 2025
  • August 2025
  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • January 2023

Tags

Certificates Education Instructor Languages School Member

Building reliable software solutions for modern businesses. Sharing practical tutorials and real-world project insights to help developers grow with confidence.

GET HELP

  • Home
  • Portfolio
  • Privacy Policy
  • Terms & Conditions
  • Disclaimer
  • Contact Us

PROGRAMS

  • Software Development
  • Performance Optimization
  • System Architecture
  • Project Consultation
  • Technical Mentorship

CONTACT US

  • Netaji Subhash Place (NSP) Delhi
  • Tel: + (91) 8287315524
  • Email: contact@codewithcoffie.com

Copyright Β© 2026 LearnPress LMS | Powered by LearnPress LMS