Swap two objects in python

Swapping the contents of two objects in python is so simple you wouldn’t believe.

// yes, it's as simple as reassigning them.
a,b = b,a

So how does this work?
1. First, the right-hand side b,a is evaluated: this means a tuple of two elements is created in memory. The two elements are the objects designated by the identifiers b and a, that existed before the instruction was encountered.

After the creation of this tuple, no assignments of this tuple object have been made yet.

2. Then, the left-hand side is evaluated: this means the tuple is assigned to the left-hand side. Since the left-hand side is composed of two identifiers, the tuple is unpacked in order to assign the first identifier a to the first element of the tuple (the object that was formerly b before the swap) and the second identifier b is assigned to the second element of the tuple (the object that was formerly a before the swap).
This mechanism has effectively swapped the objects assigned to the identifiers a and b.

Advertisements