Reputation: 1
When I try to swap 2 items in a list, some strange things happen. When trying this code, the nums is updated to [4, 1, 3, 1]
:
i = 1
nums = [-1, 4, 3, 1]
nums[i]
nums[nums[i]-1] = nums[nums[i]-1]
nums[i]
However, when the command is
nums[nums[i]-1]
nums[i] = nums[i]
nums[nums[i]-1]
The nums is [-1, 1, 3, 4]
, which is what I expect.
I am totally confused about what happens in the two cases. Could anyone explain this clearly?
Upvotes: 0
Views: 52
Reputation: 2380
What you're trying to do is called multiple assignment in Python. Consider the following codes:
[print(0)][0], [print(1)][0] = print(2), print(3)
Outputs:
2
3
0
1
[print(0)][0] = [print(1)][0] = [print(2)][0] = [print(3)][0]
Outputs:
3
0
1
2
You might have found that for either of these assignments, the right-hand operands are evaluated first from left to right, and then it goes with left-hand operands.
It works the same way in the code you provided.
i = 1
nums = [-1, 4, 3, 1]
nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
In the right-hand side, nums[nums[i]-1]
is evaluated to be nums[3]
, which gives integer 1
, and then nums[i]
is evaluated to be nums[1]
, which gives integer 4.
Now it's the turn to assign values for the left-hand operands. At the moment, nums[i]
refers to nums[1]
, thus 1
is assigned to nums[1]
. Note that nums[1]
equals 1
now, and then the interpreter finds that nums[nums[i]-1]
refers to nums[1-1]
which is nums[0]
! Then 4
is assigned to nums[0]
, giving you the result [4, 1, 3 ,1]
.
However, if you switch the operands, the order of this multiple assignment will change, and the result will be different. Similarily, the evaluation process is as follows:
nums: [-1, 4, 3, 1]
nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]
nums: [-1, 4, 3, 1]
nums[nums[i]-1], nums[i] = 4, nums[nums[i]-1]
nums: [-1, 4, 3, 1]
nums[nums[i]-1], nums[i] = 4, 1
nums: [-1, 4, 3, 1]
nums[3], nums[i] = 4, 1
nums: [-1, 4, 3, 4]
nums[i] = 1
nums: [-1, 1, 3, 4]
Upvotes: 1