Signup/Sign In

Swapping three Variables without using any Temporary Variable in Python

Posted in Tricks   LAST UPDATED: AUGUST 27, 2021

    Suppose we have been given three variables, and we have been asked to swap them, with a condition that any temporary variable shouldn't be used, what would your approach be?

    We will show you a few approaches which can be used to achieve the same.

    Sample input: a = 3, b = 7, c = 0

    Sample output: a = 0, b=3, c = 7

    1. Using arithmetic operators

    The idea is to sum two numbers and store them in one variable. The other variable can be found by subtracting the value to be found from the sum.

    Let's see this with help of an example,

    a = 11
    b = 89
    c = 37
    print("Before swapping a = ",a,", b = ",b,", c = ",c) 
    a = a + b + c
    b = a - (b+c)
    c = a - (b+c)
    a = a - (b+c)
    print("After swapping a = ",a,", b = ",b,", c = ",c) 


    Before swapping a = 11 , b = 89 , c = 37
    After swapping a = 37 , b = 11 , c = 89

    Note: An important point to note here is that when the variables hold large values, the above method causes the stack to overflow. The solution to this is to use a different method when encountering large values.

    2. Using bitwise XOR operator

    The only catch here is to store every integer value as a list data structure since every bit needs to be manipulated.

    a = [11]
    b = [89]
    c = [37]
    print("Before swapping a = ",a,", b = ",b,", c = ",c) 
    a[0] = a[0] ^ b[0] ^ c[0] 
    b[0] = a[0] ^ b[0] ^ c[0] 
    c[0] = a[0] ^ b[0] ^ c[0]  
    a[0] = a[0] ^ b[0] ^ c[0] 
    print("After swapping a = ",a,", b = ",b,", c = ",c) 


    Before swapping a =  [11] , b = [89] , c =  [37]
    After swapping a =  [37] , b = [11] , c =  [89]

    Also, this technique works for integer values. If you add more than one integer value in the list only the first integer value will be swapped.


    In this post, we understood how three variables can be swapped without the usage of a temporary variable in Python. This is quite a frequent trick question in interviews. Do let us know in the comment section below about your method.

    You may also like:

    About the author:
    I love writing about Python and have more than 5 years of professional experience in Python development. I like sharing about various standard libraries in Python and other Python Modules.

    Want to learn coding and don't know where to start?

    Try out our Interactive Courses for Free 🥳 😯 🤩
    learn to code footer Ad