Why is the [:] needed in the array. I understand that slicing using [:] creates a copy but why is the copy needed here? Also I tried creating copy with a temp variable which didn't work. This is for array rotation problem.
class Solution:
def rotate(self, nums, k):
k=k%len(nums)
g = len(nums) -k
nums[:] = nums[g:] nums[:g]
A=Solution()
MyList=[1,2,3,4]
A.rotate(MyList,2)
assert (MyList == [3, 4, 1, 2])
CodePudding user response:
After the assignment to MyList
, the list [1,2,3,4]
is created and MyList contains a reference to it.
When you call the function rotate()
with MyList
passed in as the nums
argument, nums contains a reference to the same list [1,2,3,4]
that MyList
refers to.
If you want to modify that list within the rotate()
function, you can do something like nums[0] = 99
or nums[1:2] = [33,66]
or nums[:] = nums[g:] nums[:g]
and these will act on the same list that was created in the original assignment to MyList
.
However, if instead you were to write nums = nums[g:] nums[:g]
inside the rotate()
function, this would simply update nums
to now be a reference to a brand new list (the result of the
operation on nums[g:]
and nums[:g]
) which is completely different from the object that MyList
refers to.
And this is the reason that the [:]
syntax is needed on the left-hand side of the assignment to nums[:]
.
CodePudding user response:
The reason is because, inside of the function definition, 'nums' is a local variable that references whatever object was passed in as a function argument. Reassigning that variable does not change the object passed in, only the reference.
What the code:
templist = nums[g:] nums[:g]
nums = templist
does is assign the local variable 'nums', inside of rotate, to point towards the templist object. The object passed in is unchanged.
In the case of the working code, [:] is NOT creating a copy of the list. Instead it is slice notation, telling the 'num' object to loop through its values and assign them to the values gives on the right of the = sign. It is mostly equivalent to:
templist = nums[g:] nums[:g]
for i in range(len(templist)):
nums[i] = templist[i]
CodePudding user response:
Well, the answer is: you don't! nums[:] = ... means that you are assigning everything in nums to something. Line five is the same as
nums = nums[g:] nums[:g]
don't forget to write
return nums
at the end of the function to return nums.