0

I can't understand why python swapping is working differently in the following example. Could someone please explain? I'm using python 3.6.9.

i = 0
perm = [2, 0, 1, 3]
perm[i], perm[perm[i]] = perm[perm[i]], perm[i]
print(perm)
[1, 2, 1, 3]

perm = [2, 0, 1, 3]
perm[perm[i]], perm[i] = perm[i], perm[perm[i]]
print(perm)
[1, 0, 2, 3]
vj1
  • 5
  • 2
  • Does this answer your question? [Understand Python swapping: why is a, b = b, a not always equivalent to b, a = a, b?](https://stackoverflow.com/questions/68152730/understand-python-swapping-why-is-a-b-b-a-not-always-equivalent-to-b-a-a) – Czaporka Jul 08 '21 at 09:44

1 Answers1

1

In python, a,b = b,a means t = a; a = b; b = t; sequentially. In the second case, it exchange the values at index 0 and index 2.
In the first case, after assigning the value to perm[i], perm[i] became 1, so the next step become to assign value at index 0 to index 1.

Jiaju Huang
  • 79
  • 1
  • 2