Suppose we have a list a=[1,2,3]
and I need to copy elements of a
to new list b
.
we can do a=b
but both a
and b
point to the same list. Hence mutating either of them mutates both the lists.
>>> a=b
>>> a
[1, 2, 3]
>>> b
[1, 2, 3]
>>> b.append(4)
>>> a,b
([1, 2, 3, 4], [1, 2, 3, 4])
>>> a.append(5)
>>> a,b
([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
>>> a is b
True
>>> id(a),id(b)
(2287659980360, 2287659980360)
To avoid this we can do b=a[:]
. a[:]
creates a different list with the same values of a
. Now, even if I mutate a
, b
will not be affected and vice-versa. b
and b[:]
are two different lists.
>>> b=a[:]
>>> a,b
([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
>>> a.append(6)
>>> a,b
([1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5])
>>> b.append(6)
>>> a,b
([1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6])
>>> a is b
False
>>> id(a),id(b)
(2287659980360, 2287653308552)
Now, if I do b[:]=a
my list b
is being mutated. But b[:]
is another list right? Both b
and b[:]
point to different lists right? Correct me if I'm wrong. Why is b
being changed if I mutate b[:]
. What am I missing?
>>> a=['a','b','c']
>>> b[:]=a
>>> a,b
(['a', 'b', 'c'], ['a', 'b', 'c'])
>>> id(b),id(b[:])
(2287653308552, 2287660267080)
>>> b is b[:]
False