7

I have seen people using [:] to make a swallow copy of a list, like:

>>> a = [1,2,3,4]
>>> b = a[:]
>>> a[0] = 5
>>> print a
[5, 2, 3, 4]
>>> print b
[1, 2, 3, 4]

I understand that. However, I have seen pleople using this notation when assigning to lists as well, like:

>>> a = [1,2,3,4]
>>> b = [4,5,6,7]
>>> a[:] = b
>>> print a
[4, 5, 6, 7]
>>> print b
[4, 5, 6, 7]

But I don't really understand why they use [:] here. Is there a difference I don't know?

jchanger
  • 739
  • 10
  • 29
XNor
  • 638
  • 3
  • 8
  • 27

3 Answers3

7

There is indeed a difference between a[:] = b and a = b.

>>> a = [1,2,3,4]
>>> b = [4,5,6,7]
>>> c = [8,9,0,1]
>>> c = b
>>> a[:] = b
>>> b[0] = 0
>>> a
[4, 5, 6, 7]
>>> c
[0, 5, 6, 7]
>>> 

When you write a = b, a is a reference to same list as b: any change in b will affect a

when you write a[:] = b a is a list initialized with the elements of b: a change in b will not affect a


And there also a difference between a[:] = b and a = b[:].

>>> a = [1,2,3,4]
>>> b = [4,5,6,7]
>>> c = a
>>> a = b[:]
>>> a
[4, 5, 6, 7]
>>> c
[1, 2, 3, 4]
>>> a = [1,2,3,4]
>>> b = [4,5,6,7]
>>> c = a
>>> a[:] = b
>>> a
[4, 5, 6, 7]
>>> c
[4, 5, 6, 7]

With a = b[:], you create a new list with the elements from b, if another variable pointed to a it is not affected

With a[:] = b, you change the elements of a. If another variable pointed to a it is also changed.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
4

Yes , when you use [:] in the left side , it changes (mutates) the list in place , instead of assigning a new list to the name (variable). To see that , try the following code -

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

You would see both 'a' and 'b' changed .

To see the difference between above and normal assignment , try the below code out -

a = [1,2,3,4]
b = a
a = [5,4,3,2]
print(a)
print(b)

You will see that only 'a' has changed , 'b' still point to [1,2,3,4]

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • I think you mean I wouldn't see both changed? Since `a[:]` is a swallow copy of itself that doesn't point to `b` anymore? – XNor Aug 21 '15 at 12:43
  • 1
    When used on the left side of assignment operator they are not creating copies. They are for mutating the list in place . – Anand S Kumar Aug 21 '15 at 12:46
2

It's more about how it copies the list than anything. Example:

>>> a = [1, 2, 3, 4]
>>> b = [4, 5, 6, 7]
>>> a = b
>>> b[0] = 9
>>> a
[9, 5, 6, 7]
>>> b
[9, 5, 6, 7]

Here, a now references b, so changing a value of b will also affect a.

>>> a = [1, 2, 3, 4]
>>> b = [4, 5, 6, 7]
>>> a[:] = b
>>> b[0] = 9
>>> a
[4, 5, 6, 7]
>>> b
[9, 5, 6, 7]

In the case of using slicing, it is only a shallow copy of the elements of the list, so a change in b won't affect a. Hope that helps clear things up.

maccartm
  • 2,035
  • 14
  • 23