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

gives unexpected and wrong output 4,1,3,1 whereas,

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

gives expected correct output -1,1,3,4

Can anyone justify why using a variable k in swapping is not leading to the correct output ?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • To start with , maybe expression arr[arr[k]-1] has the new value of arr[k] in index arr[k]-1 ? – Anurag Kedia Dec 26 '21 at 14:52
  • 2
    Explain exactly what you want to do. For any `k`, `arr[k]-1` isn't guaranteed to be in the list, so that's not a safe index to use for swapping. For example, if `arr = [1, 9, 3, 5]` – OneCricketeer Dec 26 '21 at 14:53
  • 4
    It's related to the evaluation order [Multiple assignment and evaluation order in Python](https://stackoverflow.com/questions/8725673/multiple-assignment-and-evaluation-order-in-python). `arr[arr[k]-1]` uses the newly assigned `arr[k]` value. – shriakhilc Dec 26 '21 at 14:55

1 Answers1

1

I think it's because the 4 at index 1 gets swapped at some point. so when we swap 1 and for for the first time is might be okey.. but then they are already swapped.. so the value of k-1 gets changed.

Himanshu Jangid
  • 369
  • 4
  • 15