Why assign a new value to a list fragment, you 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 a and [:] are different, why are they connected? What is the difference between these two solutions?

+4
source share
1 answer

a[:] does not have the same meaning / works differently in both examples

In the first example:

a[:] = [4,5,6]

you assign ausing the slice assignment . It changes the contents a. This way to completely change the list without changing its link.

In the second example:

a[:].append(4)

a[:]creates a shallow copy of the list, like list(a)or copy.copy(a), then the code adds 4to this very copy a, therefore it adoes not change.

+3
source

Source: https://habr.com/ru/post/1689115/


All Articles