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?
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.
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]
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