Search code examples
pythonalgorithmswapcpython

How swapping variables is implemented in Python?


How does the below code work in Python:

a = input()
b = input()
a, b = b, a  # STATEMENT 1
print(a, b)

Does the statement 1 create a third variable in Python heap memory space to swap the two numbers or does it use some algorithm to do the swap?


Solution

  • It's a simple bytecode operation which doesn't need any intermediate variables to do the swap. See this demo:

    import dis
    
    code = '''
    a = input()
    b = input()
    a, b = b, a
    '''
    
    dis.dis(code)
    

    Output:

     2           0 LOAD_NAME                0 (input)
                 2 CALL_FUNCTION            0
                 4 STORE_NAME               1 (a)
    
     3           6 LOAD_NAME                0 (input)
                 8 CALL_FUNCTION            0
                10 STORE_NAME               2 (b)
    
     4          12 LOAD_NAME                2 (b)
                14 LOAD_NAME                1 (a)
                16 ROT_TWO
                18 STORE_NAME               1 (a)
                20 STORE_NAME               2 (b)
                22 LOAD_CONST               0 (None)
                24 RETURN_VALUE
    
    

    Note: Like bytecode as a whole, this is of course just an implementation detail of CPython.