Today learning python, suddenly found no swap function, how to exchange two numbers it, do handwriting exchange efficiency that bad
We look at an example
a = 1 b = 2 a,b = b,a print(a,b)
In fact, very simple principle, but I was wondering for a long time, may fall into the programming process of thinking, has been entangled in the end who should assign a and b, how to exchange, like a long time Baidu, instantly clear
personal idea:
Variable is simply to store a value, we use another variable with the new variable to point to when, in fact, points to another variable is stored
This can be so understanding of, a, b = b, a fact disguised to the front of a, b two variables point to the value of their
Then a = b b = a and why not do it
A = b because the front, has a variable value b of the point, and b = a put back a passed point value and b
Results in a = b
In fact, a, b = b, a step should be run
1, to find the value of b in memory, for example, the value of a: b = 1 a = 2
2, re-assignment a, b = 1,2