# 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?
a[:] does not have the same meaning / works differently in both examples
a[:]
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.
a
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.
list(a)
copy.copy(a)
4
Source: https://habr.com/ru/post/1689115/More articles:Как отправить данные из фрагмента в глубокий вложенный компонент? - graphqlRegx for a domain with "www" or without "www" - javascriptКак решить проблему "плохой указатель в барьерах записи" в cgo, когда библиотека C использует непрозрачные указатели на структуру - cJava requires a default method - javaMake sure the JUnit Extension throws a specific exception - javaHow to test extensions - junit5Is memory released after each iteration when matching a list? - listFirebase + Ionic3 Error: disallowed_useragent - angularGo id for structure in package? - goОшибка android.system.ErrnoException - javaAll Articles