2

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?

gkaz
  • 21
  • 4
  • 2
    The tuple on the right side of the assignment is evaluated first (left to right) and is then assigned to the tuple elements on the left side one by one left to right. "arr[0]" gets its new value first so just swap the order in each tuple. – Michael Butscher Jan 17 '21 at 03:36
  • It makes sense now. I did not know that this was how its executed. I thought both get assigned simultaneously. I could not notice the difference when I was doing regular swapping between two elements i and j. – gkaz Jan 17 '21 at 03:44

4 Answers4

2

you should first change arr[arr[0]] value then arr[0] value . so a place change will solve problem .

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

[2, 1, 3, 4, 5]
0

You prob. can try this to see it help you:

arr = [1, 2, 3, 4, 5]

for i in range(0,len(arr)-1, 2):
    arr[i], arr[i+1] = arr[i+1], arr[i]

print(arr)

Output:

[2, 1, 4, 3, 5]
Daniel Hao
  • 4,922
  • 3
  • 10
  • 23
0
arr = [1, 2, 3, 4, 5]
#the prob with your code is you are first assigning the vaue and changing it
arr[arr[0]],arr[0] =arr[0],arr[arr[0]]
print(arr)
[2, 1, 3, 4, 5]

just reverse the order then it willbe okay,it's working fine now

0

Python swaps values based on location. When you see the opcode for a, b = b, a, you will see that I will call a method called ROT_TWO(). You can find the reference for that at here and cpython implementation at here.

Let's go with first two index 0 and 1.

First it will push 0 into a stack and then 1. Now it pops which has location(index) 1 at that location we have value 2 in the array. It swaps.

Now it pops location(index) 0. Now we have value 2 at the location 0. so that's why we have value 2 at index 0 and 1.

Hope this answers our question.