27

Simple and short question. Swapping two variables in Python is very easy: a, b = b, a. That's ok, I have no objections :) But I'm interested how it works internally? Does it create some temporary variable by itself or it is something more interesting (I bet so)?

1 Answer 1

43

Python source code is converted to bytecode before it is executed. You can see how the swap works internally by using the disassembler dis to see what the bytecode looks like:

import dis
>>> def f(a,b): a, b = b, a
>>> dis.dis(f)
  1           0 LOAD_FAST                1 (b)
              3 LOAD_FAST                0 (a)
              6 ROT_TWO             
              7 STORE_FAST               0 (a)
             10 STORE_FAST               1 (b)
             13 LOAD_CONST               0 (None)
             16 RETURN_VALUE 

In simple terms, it pushes the values of a and b on the stack, rotates (swaps) the top two elements, then pops the values again.

See also:

2
  • Great. I had wrong thought that when we use , between two o more expressions , Python will pack them into a (here temporary) "tuple". Maybe this isn't the case here because on the left hand side there is exactly these two a and b. Is that the reason there is no BUILD_TUPLE in instructions?
    – S.B
    Commented Jun 4, 2021 at 7:59
  • 1
    @S.B yes this is a special case, optimized by Python. In general, a , will create a tuple.
    – jthulhu
    Commented Mar 24, 2023 at 12:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.