A shortcut way to copy a list or a string is to use the slice operator [:] . This will make a shallow copy of the original list keeping all object references the same in the copied list.
[:] is the array slice syntax for every element in the array. This answer here goes more in depth of the general uses: Explain Python's slice notation. del arr # Deletes the array itself del arr[:] # Deletes all the elements in the array del arr[2] # Deletes the second element in the array del arr[1:] # etc..
Answer: The double colon is a special case in Python's extended slicing feature. The extended slicing notation string[start:stop:step] uses three arguments start , stop , and step to carve out a subsequence. It accesses every step -th element between indices start (included) and stop (excluded).
I came accross the following code:
# O(n) space def rotate(self, nums, k): deque = collections.deque(nums) k %= len(nums) for _ in xrange(k): deque.appendleft(deque.pop()) nums[:] = list(deque) # <- Code in question
What does nums[:] =
do that nums =
does not? For that matter, what does nums[:]
do that nums
does not?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With