News for hackers. Stuff that matters.
Re:Swapping two Numbers without Temporary Variables by kmill on Thursday March 24, 2022 @04:09PM (#30794749)
For what it's worth, the Python example isn't too relevant since it's hiding a number of intermediate variables (that said, swapping without intermediate variables tends to be more of a curiosity anyway -- and a motivated person can "well actually" the whole concept into oblivion). What it does is push a and b onto the interpreter stack, then (in the version of Python 3 I'm running, though the more recent one should be similar) it pops those into two local C variables and pushes them in a different order, then it pops them and stores them into local python variables.

  import dis
  
  def swap(a, b):
      a, b = b, a
      return a
  
  dis.dis(swap)
Output:

  4           0 LOAD_FAST                1 (b)
              2 LOAD_FAST                0 (a)
              4 ROT_TWO
              6 STORE_FAST               0 (a)
              8 STORE_FAST               1 (b)

  5          10 LOAD_FAST                0 (a)
             12 RETURN_VALUE
Implementation of ROT_TWO https://github.com/python/cpython/blob/bc85eb7a4f16e9e2b6fb7...

There are no comments on this comment yet.