hcnhcn012
hcnhcn012

Reputation: 1425

Why assign a new value to slice of a list can change the original list in python

# 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

Answers (1)

Jean-François Fabre
Jean-François Fabre

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

Related Questions