I am not sure why a[0], a[a[0]] = a[a[0]], a[0] this one does not do the swap?
>>> nums
[2, 1, 0]
>>> a = [2,1,0]
>>> a[0], a[a[0]] = a[a[0]], a[0]
>>> a
[2, 1, 0]
>>> a[0]
2
>>> a[0],a[2] = a[2], a[0]
>>> a
[0, 1, 2]
My guess is that the implementation of a, b = b, a syntax is something like:
tmp = a[0] (tmp = 2)
a[0] = a[a[0]] (a[0] = a[2] = 0)
a[a[0]] = tmp (a[a[0]] = a[0] = tmp = 2)
Then I checked the implementation of swap function in C++. I know nothing about C++, but it looks like the idea is the same
:
http://www.cplusplus.com/reference/algorithm/swap/
The behavior of these function templates is equivalent to:
template void swap (T& a, T& b)
{
T c(std::move(a)); a=std::move(b); b=std::move(c);
}
template void swap (T (&a)[N], T (&b)[N])
{
for (size_t i = 0; i
}
we have c = a, then a = b and b = a
So why C++ swap function does not have this problem?
And how to write this kind of swap function in a pythonic way?
解决方案
This kind of the behaviour is indeed related to the way Python evaluates the expression of the type
a,b=b,a
In fact, what Python does is first it "prepares" the values of the right side by creating a tuple (b,a). Then this tuple is unpacked and assigned to the variables in the reverse order.
It is important to note that although Python uses references to objects the objects the variable names refer to may change if they refer to values of immutable type. It is not so with mutable types (illustrated by example in Python FAQ).
To break down the example with mutable types (lists) that you used:
a = [2,1,0]
a[0], a[a[0]] = a[a[0]], a[0]
a[a[0]] takes the value from the a[0] element (equal to 2) of the list a (value 0).
a[0] is 2 hence the tuple created is (0,2)
Tuple (0,2) is unpacked and 0 replaces 2 in the list (0th element).
Now, a[a[0]] can be read as: take 0th element of list a (which is currently 0) and then replace the value in the list at that place with 2 from tuple unpacking (now 0 is replaced by 2 - which make the operation look like it does nothing to the list).
As suggested in the answer from von Oak changing the order helps because the step from the point 4. above does not replace the value again.
I suggest you refer to passing by assignment answer to understand functions and parameter passing.