Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swap values of variables

Good day,

Could you please explain in what order the code executes.

variable_1 = 1
variable_2 = 2

variable_1, variable_2 = variable_2, variable_1

Why is the output 2,1 and not 2,2?
Isn’t variable_1 already become of value 2?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In the code you provided, the output is indeed 2, 1 and not 2, 2. This is because in the third line of the code, you are using a tuple assignment to swap the values of variable_1 and variable_2.

In a tuple assignment, the right-hand side of the assignment is evaluated before the left-hand side. In other words, the values of variable_1 and variable_2 are swapped before they are assigned to the variables on the left-hand side of the assignment. This is why the output is 2, 1 and not 2, 2.

Here is how the code is executed step by step:

  1. variable_1 is assigned the value 1.

  2. variable_2 is assigned the value 2.

  3. The righthand side of the tuple assignment is
    evaluated, which swaps the values of variable_1 and
    variable_2. At this point, variable_1 has the value 2
    and variable_2 has the value 1.

  4. The left-hand side of the tuple assignment is evaluated, which assigns the values of variable_1 and variable_2 to the variables on the left-hand side of the assignment. This means that variable_1 is now assigned the value 2 and variable_2 is now assigned the value 1.

To summarize, the tuple assignment is evaluated from right to left, which means that the values of variable_1 and variable_2 are swapped before they are assigned to the variables on the left-hand side of the assignment. This is why the output is 2, 1 and not 2, 2.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading