The easiest way is to check how nums
looks like after every operation (with print(nums)
in scratch or calling it (nums
) in terminal). Next time, try it yourself.
In A:
With the first line (nums[:k] = nums[len(nums)-k:]
): nums = [5, 6, 7, 4, 5, 6, 7]
– you’ve substituted nums[0:3]
(1, 2, 3
) with nums[4:7]
(5, 6, 7
).
Then, with the second line (nums[k:] = nums[:len(nums)-k]
): nums = [5, 6, 7, 5, 6, 7, 4]
– you’ve substituted nums[3:7]
(4, 5, 6, 7
) with nums[0:4]
(5, 6, 7, 4
).
In B:
You’ve done this operations “in place”, without changing the nums
between them. You’ve “grabbed” 1, 2, 3, 4
and 5, 6, 7
, made list [5,6,7,1,2,3,4]
and assigned it to nums
overwriting its value ([1,2,3,4,5,6,7]
).
3
solved Python reverse list with k steps, in-place operator vs standard operator [closed]