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 ?

3
  • To start with , maybe expression arr[arr[k]-1] has the new value of arr[k] in index arr[k]-1 ? Commented Dec 26, 2021 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] Commented Dec 26, 2021 at 14:53
  • 4
    It's related to the evaluation order Multiple assignment and evaluation order in Python. arr[arr[k]-1] uses the newly assigned arr[k] value. Commented Dec 26, 2021 at 14:55

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.