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)?
Simple and short question. Swapping two variables in Python is very easy: a, b
Share
Python source code is converted to bytecode before it is executed. You can see how the swap works internally by using the disassembler
disto see what the bytecode looks like: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: