I am trying to solve the LeetCode problem 189. Rotate Array in Python:
Given an array, rotate the array to the right by k steps, where k is non-negative.
class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """
The following code works:
n = len(nums)
k = k % n
nums[k:], nums[:k] = nums[:-k], nums[-k:]
But if I change the order of the assignments in the last line, i.e. replace it with
nums[:k], nums[k:] = nums[-k:], nums[:-k]
the code doesn't work for the case of k=0. Clearly in this case, nums[:k] and nums[:-k] would be empty and the sizes of the lists on the left hand side and the right hand side don't match, but somehow the first code works and the second one doesn't.
Can someone explain?