What does the colon do when assigning to the list [:] = [...] in Python

I came by 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[:] =what nums =not? In this case, what does nums[:]that numsfail?

+13
source share
2 answers

This syntax is a fragment assignment. Slice [:]means the whole list. The difference between nums[:] =and nums =is that the latter does not replace the items in the original list. This is observed when there are two links to the list.

>>> original = [1, 2, 3]
>>> other = original
>>> original[:] = [0, 0] # changes what both original and other refer to 
>>> other # see below, now you can see the change through other
[0, 0]

To see the difference, simply remove [:]from the task above.

>>> original = [1, 2, 3]
>>> other = original
>>> original = [0, 0] # original now refers to a different list than other
>>> other # other remains the same
[1, 2, 3]

, list - , ,

>>> list = [1,2,3,4]
>>> list[:] = [...]
>>> list
[Ellipsis]
+32

nums = foo nums , foo.

nums[:] = foo , nums, foo.

:

>>> a = [1,2]
>>> b = [3,4,5]
>>> c = a
>>> c = b
>>> print(a)
[1, 2]
>>> c = a
>>> c[:] = b
>>> print(a)
[3, 4, 5]
+4

Source: https://habr.com/ru/post/1606337/


All Articles