Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does variable swapping work internally?

Tags:

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)?

like image 271
Ignas Butėnas Avatar asked Dec 21 '11 08:12

Ignas Butėnas


People also ask

How does Python swap work?

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.

How does a b/b a work in Python?

When the numbers match, it's a one-to-one unpacking. It appears that a, b = b, a involves the one-to-one unpacking. However, it turns out that Python uses an optimized operation (i.e., ROT_TWO ) to swap the references on a stack. Such swapping happens when three variables are involved.


1 Answers

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:

  • Python Bytecode Instructions
like image 146
Mark Byers Avatar answered Sep 23 '22 19:09

Mark Byers