Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
George John

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.

Explaination

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.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.