python - How does variable swapping work internally? -
simple , short question. swapping 2 variables in python easy: a, b = b, a
. that's ok, have no objections :) i'm interested how works internally? create temporary variable or more interesting (i bet so)?
python source code converted bytecode before executed. can see how swap works internally using disassembler dis
see bytecode looks like:
import dis >>> def f(a,b): a, b = b, >>> 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, pushes values of , b on stack, rotates (swaps) top 2 elements, pops values again.
see also:
python bytecode instructions python
No comments:
Post a Comment