-1

I have the next test task:

arr = [4,3,2,1]
arr[0], arr[arr[0]-1] = arr[arr[0]-1], arr[0]
print(arr)

I'd expect the result as [1,3,2,4] as we assign new values to elements of the list. But it gives the result as the initially [4,3,2,1].

Why does it work in this way? Why does it change not the list?

If to make it in the next way: arr[0], arr[3] = 1 , 4

it works...

affogato
  • 3
  • 3

2 Answers2

1

Have a look at order in which interpreter evaluates

arr[0], arr[arr[0]-1] = arr[arr[0]-1], arr[0]

So first it evaluates RHS from left to right and above line is equivalent to

arr[0], arr[arr[0]-1] = 1, 4

Now it start to evaluate from left to right the LHS and assign 1 to arr[0], at that point arr is [1, 3, 2, 1]

it now evaluates arr[arr[0]-1] and gets arr[1-1] or arr[0]. So it assign 4 to index 0. And the result is [4, 3, 2, 1]

Note, it will work if you swap the element, e.g.

arr = [4,3,2,1]
arr[arr[0]-1], arr[0]  = arr[0], arr[arr[0]-1]
print(arr)

output

[1, 3, 2, 4]

However, this complicated indexing doesn't make sense IMHO.

buran
  • 13,682
  • 10
  • 36
  • 61
0

It is because of the way you are assigning two things.

arr[0], arr[arr[0]-1] = arr[arr[0]-1], arr[0]

What it does is it calculates the RHS first as 1, 4 and now, on LHS, first arr[0] is assigned as 1, and now it uses this arr[0]=1 to solve arr[arr[0]-1] which again turns out as arr[0] which gets assigned to 4. So basically, it does two tasks in sequence, which cancels the overall operation (for the array you have defined).

Try using arr = [4,2,5,3] to see the effect of what I am conveying. For some values, it will also lead to Index out of range errors.