I'm having trouble understanding what is going on behind the scenes for this simple piece of code:
def changeArray(arr): for i in range(len(arr)): arr[i], arr[arr[i] - 1] = arr[arr[i] - 1], arr[i] print(arr) return(arr)
The code assumes that the array has integers from 1 to n as its elements. The output for this code when the input [1,3,4,2] is:
[1, 3, 4, 2] [1, 4, 4, 3] [1, 4, 4, 3] [1, 4, 4, 3] Out[8]: [1, 4, 4, 3]
while I expected it to print and return this:
[1, 3, 4, 2] [1, 4, 3, 2] [1, 4, 3, 2] [1, 2, 3, 4] Out[8]: [1, 2, 3, 4]
Why do values โโchange at all when the code is just a replacement for elements?
Edit:
It turns out that swapping the swap order fixes the problem:
def changeArray(arr): for i in range(len(arr)): arr[arr[i]-1], arr[i] = arr[i], arr[arr[i]-1] print(arr) return(arr)
This gives the following result:
[1, 3, 4, 2] [1, 4, 3, 2] [1, 4, 3, 2] [1, 2, 3, 4] Out[8]: [1, 2, 3, 4]
How did the reordering change, as expected, and vice versa did something else?