Just wondering what happens when I run
nums[i], nums[nums[i] - 1] = nums[nums[i] - 1], nums[i]
in python3.
I know it works when I do like
x = nums[i] - 1
nums[i], nums[x] = nums[x], nums[i]
But still don't know what exactly happened.
Just wondering what happens when I run
nums[i], nums[nums[i] - 1] = nums[nums[i] - 1], nums[i]
in python3.
I know it works when I do like
x = nums[i] - 1
nums[i], nums[x] = nums[x], nums[i]
But still don't know what exactly happened.
Python rules are quite specific.
When evaluating a = b = c = ... = z
, the right hand side is evaluated, and then this is assigned, in order to a
then b
, then c
, ...
When assigning a value to a normal tuple, the value assigned must have the same length as the tuple being assigned to. The first value is assigned to the first part of the tuple, then the second value is assigned to the second part of the tuple, and so on.
Between these two rules, what happens in the above code is clear. These steps occur in order:
nums=[4,8,3,7,5]
print('before',nums)
i=3
nums[i], nums[i - 1] = nums[i - 1], nums[i]
print('after',nums)
before [4, 8, 3, 7, 5]
after [4, 8, 7, 3, 5]
the code will bec executed from the most right to left
nums=[4,8,7,3,5]
i=3
>nums[i], nums[nums[i] - 1] = nums[nums[i] - 1], nums[i]
>nums[i], nums[nums[i] - 1] = nums[3 - 1], 3
>nums[i], nums[nums[i] - 1] = nums[2], 3
>nums[i], nums[nums[i] - 1] = 7, 3
#first element
>nums[i] ----> 7
>nums[3] ----> 7
>nums=[4,8,7,7,5]
#second element
>nums[nums[i] - 1] ---> 3
>nums[nums[3] - 1] ---> 3 #nums[3] became 7
>nums[7 - 1] ---> 3
>nums[6] ---> 3 #index out of range