vj1
vj1

Reputation: 5

Inconsistent swapping in python

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]

Upvotes: 0

Views: 33

Answers (1)

Jiaju Huang
Jiaju Huang

Reputation: 79

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.

Upvotes: 1

Related Questions