a,b = b,a in python vs std::swap() in C++

  • A+

I know that a,b = b,a is basically assigning a tuple (a,b) the values of another tuple (b,a). This is, essentially, swapping the values form a to b and from b to a. Thus, causing a "swap".

This is the functionality of the swap() function in C++.

From research, I have seen that C++'s swap() function uses a third temporary variable to perform the swap. I haven't been able to find how is a,b = b,a implemented in python.

How is a,b = b,a implemented?

Does python also use a third temporary variable? If it doesn't, how does it work?

How do both operations compare in terms of speed? I'm guessing that if python also uses a third variable, the difference in execution time would be due to python being interpreted.


For tuple assignments, Python uses the stack structure directly:

>>> import dis >>> def abc(a, b): ...     a, b = b, a ...  >>> dis.dis(abc)   2           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 python, assignments in a target list on the left-hand side are done from left to right.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: