Reputation: 1425
# sample 1
a = [1,2,3]
a[:] = [4,5,6]
print(a)
>>> [4,5,6]
# sample 2
a = [1,2,3]
a[:].append(4)
print(a)
>>> [1,2,3]
Why could this happen? The address of a and a[:] is different, why they are connected? What is the difference between these 2 solutions?
Upvotes: 4
Views: 653
Reputation: 140188
a[:]
hasn't the same meaning/works different ways in both examples
In the first example:
a[:] = [4,5,6]
you're assigning to a
using slice assignment. It changes the contents of a
. That's one way to completely change a list without changing its reference.
In the second example:
a[:].append(4)
a[:]
creates a shallow copy of the list, just like list(a)
or copy.copy(a)
, then the code appends 4
to this very copy of a
, therefore, a
isn't changed.
Upvotes: 3