I am trying to swap 2 elements in a list. I want to swap the element at index 0 to the element at index arr[0], so basically I want to swap arr[0] <-> arr[arr[0]].
I have always used this method to swap elements between indexes i and j:
arr[i], arr[j] = arr[j], arr[i]
But it does not seem to work in this case. If I do:
arr = [1, 2, 3, 4, 5]
arr[0], arr[arr[0]] = arr[arr[0]], arr[0]
print(arr)
[2, 2, 1, 4, 5]
But I would expect:
arr = [1, 2, 3, 4, 5]
tmp = arr[arr[0]]
arr[arr[0]] = arr[0]
arr[0] = tmp
print(arr)
[2, 1, 3, 4, 5]
Could anybody explain this behavior?