Python - Swap Two Variables

In this program, you will learn how to swap two variables.


Program: Swap variables using a temporary variable



    # This program to swap two variables

    x = 11
    y = 12
    
    print('The value of varable x is {} before swapping'.format(x))
    print('The value of varable y is {} before swapping'.format(y))
    
    # temp is a third variable
    temp = x
    x = y
    y = temp
    
    print('The value of varable x is {} after swapping'.format(x))
    print('The value of varable y is {} after swapping'.format(y))
            
            

Output


    The value of varable x is 11 before swapping
    The value of varable y is 12 before swapping
    The value of varable x is 12 after swapping
    The value of varable y is 11 after swapping
            

In this program, we use the temp variable to hold the value of x temporarily. Then, we put the value value of y in x. After that, we puttemp in y. So, we exchanged the values in this way.

Program: Swap variables without using a temporary variable



We have a simple construct to swap the variables in Python. The follwoing code does the same as above but without using any temporary variable.

    # This program to swap two variables without a temporary variable

    x = 10
    y = 20
    
    print('The value of varable x is {} before swapping'.format(x))
    print('The value of varable y is {} before swapping'.format(y))
    
    x, y = y, x
    
    print('The value of varable x is {} after swapping'.format(x))
    print('The value of varable y is {} after swapping'.format(y))
            
            

Output


    The value of varable x is 10 before swapping
    The value of varable y is 20 before swapping
    The value of varable x is 20 after swapping
    The value of varable y is 10 after swapping
            



The following topics can be useful to understand this program.



Related Tutorials