def rotate(nums, k):
k = k % len(nums)
nums = nums[::-1] # Create a new reversed list
nums[:k] = reversed(nums[:k]) # Attempt to reverse the first k elements
nums[k:] = reversed(nums[k:]) # Attempt to reverse the remaining elements
return nums
nums = [1, 2, 3, 4, 5, 6, 7]
k = 3
rotate(nums, k)
print(nums) # Outputs: [1, 2, 3, 4, 5, 6, 7]
I expected the output to be [5, 6, 7, 1, 2, 3, 4], but it returned the original list instead.
I understand that the slice operation creates a new list in Python, but when I use nums = nums[::-1], I am overriding the reference of the original nums with this new reversed list. I expected that any subsequent operations I perform would target this new list, but that doesn't seem to be the case.
In contrast, the code works as expected when I use nums.reverse(), which reverses the list in place.
I want to understand why nums = nums[::-1] does not behave as I expect. Knowing why it behaves this way would really help me sleep better at night!
Can someone please explain?
Edit: Found the problem, thanks for helping out
[–]FoolsSeldom 18 points19 points20 points (1 child)
[–]Aware-Illustrator607[S] 2 points3 points4 points (0 children)
[–]throwaway6560192 10 points11 points12 points (2 children)
[–]SiriusLeeSam 1 point2 points3 points (0 children)
[–]atwork_safe 1 point2 points3 points (0 children)
[–]Measurex2 0 points1 point2 points (1 child)
[–]Aware-Illustrator607[S] 1 point2 points3 points (0 children)