Element swapping in list using one line multiple assignment

1.9k Views Asked by At

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?

4

There are 4 best solutions below

0
Daniel Hao On

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]
0
Alireza Rahimi On

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
CHINNIKALYAN On
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
ghostshelltaken On

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.