Is there a standardized method to swap two variables in Python? Is there a standardized method to swap two variables in Python? python python

Is there a standardized method to swap two variables in Python?


Python evaluates expressions from left to right. Notice that whileevaluating an assignment, the right-hand side is evaluated before theleft-hand side.

Python docs: Evaluation order

That means the following for the expression a,b = b,a :

  • The right-hand side b,a is evaluated, that is to say, a tuple of two elements is created in the memory. The two elements are the objects designated by the identifiers b and a, that were existing before the instruction is encountered during the execution of the program.
  • Just after the creation of this tuple, no assignment of this tuple object has still been made, but it doesn't matter, Python internally knows where it is.
  • Then, the left-hand side is evaluated, that is to say, the tuple is assigned to the left-hand side.
  • As the left-hand side is composed of two identifiers, the tuple is unpacked in order that the first identifier a be assigned to the first element of the tuple (which is the object that was formerly b before the swap because it had name b)
    and the second identifier b is assigned to the second element of the tuple (which is the object that was formerly a before the swap because its identifiers was a)

This mechanism has effectively swapped the objects assigned to the identifiers a and b

So, to answer your question: YES, it's the standard way to swap two identifiers on two objects.
By the way, the objects are not variables, they are objects.


That is the standard way to swap two variables, yes.


I know three ways to swap variables, but a, b = b, a is the simplest. There is

XOR (for integers)

x = x ^ yy = y ^ xx = x ^ y

Or concisely,

x ^= yy ^= xx ^= y

Temporary variable

w = xx = yy = wdel w

Tuple swap

x, y = y, x


matomo