In this story of the “Why Python” series, we will talk about Why does Python only needs one statement a,b = b,a to exchange two variables directly?. You will get the link to the previous stories of this series at the end.

From the time Python’s tuple unpacking quite interesting, very concise, and easy to use.

The most obvious example is multiple assignments, that is, assigning values ​​to multiple variables in one statement:

Image for post

In this example, the two numbers on the right side of the assignment operator “=” will be stored in a tuple, which becomes (1,2), and then unpacked and assigned to the two variables to the left of the “=”.

If we write x = 1,2 directly, and then print out x, or write a tuple on the right side of the “=” sign, like this:

Image for post

When some blogs or public account articles introduce this feature, they usually follow an example, that is, based on two variables, directly exchanging their values:

Image for post

Generally speaking, the operation of transferring two variables requires the introduction of a third variable.

The reason is simple. If you want to exchange the water in the two cups, you will naturally need a third container as a relay.

However, Python’s writing method does not require intermediate variables, and its form is the same as the previous unpacking assignment.

Because of the similarity in this form, many people mistakenly believe that Python’s variable exchange operations are also based on unpacking operations.

But is it true?

I found that someone tried to answer this question, but their answer was not comprehensive enough. (Of course, many of the solutions are wrong, and many more people just know what they are, but never want to know why)

Let me put the answer to this article first: Python’s variable exchange operation is not entirely based on unpacking operation, sometimes it is, sometimes it is not!

#technology #programming #python3 #knowledge #python

Why Python allows the Exchange of Variables Directly?
1.10 GEEK