Search code examples
pythonpython-3.xlistswap

Does this way of swapping values in list use extra memory in Python?


The usual way to swap values in a list is to use a temporary variable.

temp = l[i]
l[i] = l[j]
l[j] = temp

But in python you can do this:

l[i], l[j] = l[j], l[i]

How does this second method work? Is it the exact same process? Does it use less / more memory?


Solution

  • import dis
    
    
    def swap_using_temp(a, b):
        temp = a
        a = b
        b = temp
    
    
    def swap_using_unpacking(a, b):
        a, b = b, a
    

    swap_using_unpacking does not require extra memory.

    Explanation: If you disassemble the code using dis module of both the function described then you will see that in swap_using_unpacking there is a bytecode instruction ROT_TWO which swaps the 2 topmost elements of the stack(which don't require a third variable hence no extra memory is consumed).


    
    dis.dis(swap_using_unpacking)
    
     11           0 LOAD_FAST                1 (b)
                  2 LOAD_FAST                0 (a)
                  4 ROT_TWO
                  6 STORE_FAST               0 (a)
                  8 STORE_FAST               1 (b)
                 10 LOAD_CONST               0 (None)
                 12 RETURN_VALUE
    

    dis.dis(swap_using_temp)
    
      5           0 LOAD_FAST                0 (a)
                  2 STORE_FAST               2 (temp)
    
      6           4 LOAD_FAST                1 (b)
                  6 STORE_FAST               0 (a)
    
      7           8 LOAD_FAST                2 (temp)
                 10 STORE_FAST               1 (b)
                 12 LOAD_CONST               0 (None)
                 14 RETURN_VALUE