In this section, we are going to swap two variable in one line using python. The standard way to swap two variables in python is very simple and easy−
>>> a = 20;b=30 >>> a 20 >>> b 30 >>> #Swap two variable in one line >>> a, b = b, a >>> a 30 >>> b 20
Above code generate swapped values of a and b.
Python evaluates expression from left to right. However, while evaluating an assignment, the right-hand side is evaluated before the left-hand side.
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 element are the objects designated by the identifiers b and a, that were existing before the instruction is encountered during an execution of program.
Once the tuple is created, but no assignment of this tuple object is made yet, but that’s not a issue, as python internally knows where it is.
Then the left-hand side is evaluated, that is- the tuple which is stored in memory is assigned to the left-hand side as the left-hand side is composed of two identifiers a and b. the tuple is unpacked in order that the first identifier a(left-side) is assigned by the first element of the tuple (.i.e. b) and the second identifier b is assigned by the second element of the tuple (.i.e. a).
In short, the expression: “ a, b = b, a”, first right gets assigned to first left and second right get assigned to second left at the same time therefore swap values of a and b.